'How to detect MetaMask login

How can we detect when a user signs in to MetaMask after the page has loaded? Is it necessary to resort to polling, or is there an event that a page can listen out for?



Solution 1:[1]

Using web3 version 1.0.0, the metamask provider exposes an 'update' event you can listen to on it's publicConfigStore.

web3.currentProvider.publicConfigStore.on('update', callback);

Your callback will be passed an object with 'selectedAddress' and 'networkVersion' whenever those attributes change.

Solution 2:[2]

Requesting Accounts access via 'eth_requestAccounts' is not really the best thing you can do because that will keep adding requests in metamask (bad performances) and a bad UX (popup + notifications)

the way to do it is via

const isUnlocked = await window?.ethereum?._metamask.isUnlocked();
console.debug({ isUnlocked });

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 Brian Ethier
Solution 2 Danyal Aytekin