To get the account address of the contract that is currently logged in with Metamask I use this

web3.eth.getAccounts(function(error, accounts) {
    document.getElementById('account-address').innerHTML = accounts;

How can i make it so address updates on UI when i change the account/ address in metamask, without having to refresh the website?


There is event accountsChanged provided by latest MetaMask version and you can use it like this:

if(window.ethereum) {
    window.ethereum.on('accountsChanged', function () {
        web3.eth.getAccounts(function(error, accounts) {
            document.getElementById('account-address').innerHTML = accounts;
  • great, but now i dont see anything. Like I cant see any output, not in the console and not in my ui? I dont see any output – Coding Joe Jan 17 '20 at 13:46
  • even when doing console.log(accounts); i get no output – Coding Joe Jan 17 '20 at 14:00
  • When you console.log window.ethereum what is the outcome? Also what is your metamask version? – Miroslav Nedelchev Jan 17 '20 at 14:23
  • console.log(window.ethereum) VM5925:1 Proxy {selectedAddress: "0xe56570858990aa5810220f7fd54dcaaf25aea8fa", networkVersion: "3", chainId: "0x3", _events: {…}, _eventsCount: 2, …} [[Handler]]: Object [[Target]]: MetamaskInpageProvider [[IsRevoked]]: false metamaks version is 7.7.2 – Coding Joe Jan 17 '20 at 14:30
  • Please take a look at this video I just recorded: streamable.com/gau1f – Miroslav Nedelchev Jan 17 '20 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.