web3js – How to Detect Account Change in Metamask

accountsmetamaskweb3js

When a user changes to a different account in metamask, is there a way to detect it asynchronously in code?

I currently use

this.web3.eth.getAccounts((err, accs) => {   
  this.account = accs[0];
});  

but when the account is changed, it still picks up the previous one.
Refreshing the page is not a way to go. Did anyone face this and has a solution?

Best Answer

As suggested by Metamask FAQs this might be an option:

var account = web3.eth.accounts[0];
var accountInterval = setInterval(function() {
  if (web3.eth.accounts[0] !== account) {
    account = web3.eth.accounts[0];
    updateInterface();
  }
}, 100);

edit

In the newer version metamask exposes an event that could be used to detect whether there's an account change as per new doc:

window.ethereum.on('accountsChanged', function (accounts) {
  // Time to reload your interface with accounts[0]!
})
Related Topic