'Detect MetaMask logout (Ethereum)

I've looked at the documentation here https://metamask.github.io/metamask-docs/Main_Concepts/Getting_Started

But I'm not sure how to detect a user logging out of MetaMask?



Solution 1:[1]

window.ethereum.on('accountsChanged', (accounts) => {
    // If user has locked/logout from MetaMask, this resets the accounts array to empty
    if (!accounts.length) {
      // logic to handle what happens once MetaMask is locked
    }
});

Thus, using the above you can detect lock/logout of MetaMask.

Solution 2:[2]

    window.ethereum.on('accountsChanged', function (accounts) {
      let acc = accounts[0]

acc will be undefined if they logged out.

Solution 3:[3]

From MetaMask Ethereum Provider API:

ethereum.on('accountsChanged', handler: (accounts: Array<string>) => void);

The MetaMask provider emits this event whenever the return value of the eth_accounts RPC method changes. eth_accounts returns an array that is either empty or contains a single account address. The returned address, if any, is the address of the most recently used account that the caller is permitted to access. Callers are identified by their URL origin, which means that all sites with the same origin share the same permissions.

Solution 4:[4]

Metamask documentation suggest you to refresh the page if account is changed.

const setAccountListener = (provider) => {
    provider.on("accountsChanged", (_) => window.location.reload());
    provider.on("chainChanged", (_) => window.location.reload());
  };

Then call this in useEffect

useEffect(() => {
     // Load provider

      if (provider) {
        ....
        setAccountListener(provider);
        // add more logic
      } else {
        
        console.error("Please, install Metamask.");
      }
    };

   
  }, []);

New Feature: _metamask.isUnlocked()

Metamask adds _metamask.isUnlocked() property on ethereum.

const handleAccount = (ethereum) => async () => {
  const isLocked = !(await ethereum._metamask.isUnlocked());
  if (isLocked) {
    reload();
  }
};

const setListener = (ethereum) => {
  ethereum.on("chainChanged", reload);
  ethereum.on("accountsChanged", handleAccount(ethereum));
};
const removeListener = (ethereum) => {
  ethereum.removeListener("chainChanged", reload);
  ethereum.removeListener("accountsChanged", handleAccount(ethereum));
};

const reload = () => window.location.reload();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 balajipachai
Solution 2 Peter Prographo
Solution 3 Miguel Mota
Solution 4