< All Blog
November 08, 2022
If users install the MetaMask browser extension, you can use MetaMask's Ethereum Provider API to watch Events, which implements Node.js EventEmitter
API.
When MetaMask is installed, window.ethereum
is available. It has on()
methods, and you can filter events that notify you when accounts are changed with accountsChanged
:
function handleAccountsChanged(accounts) {
console.log(accounts)
}
// register the event listener
ethereum.on('accountsChanged', handleAccountsChanged);
// deregister the event listener
ethereum.removeListener('accountsChanged', handleAccountsChanged);
If you take care of edge cases like when MetaMask is not installed, the full source code would look like as follows:
function watchAccountsChange(fn) {
const { ethereum } = window
if (ethereum) {
ethereum.on('accountsChanged', (accounts) => {
fn(accounts)
})
} else {
throw new Error('MetaMask not installed')
}
}
watchAccountsChange((accounts) => {
if (accounts.length > 0) {
const account = accounts[0]
console.log(account)
}
})