0

I'm using the next function to get the first account from user's MetaMask:

var account = web3.eth.getAccounts((error,result) => {
        if (error) {
            console.log(error);
        } else {
            return result[0];
        }
    });

However the user could have selected any other account from his MM not just the first one, or switch the account anytime. How to get the current selected account?

0

First of all your website must be allowed to connect MetaMask. This can be achieved by adding the website url in MetaMask -> Settings -> Connections. If you want dynamic solution for your users your website need to run this code whenever your it's loaded so your users don't have to deal manual whitelisting your website:

if(window.ethereum) {
    await ethereum.enable();
}

(latest MetaMask comes with window.ethereum variable)

Now after doing that you can define the following method:

function getAccounts(callback) {
    web3.eth.getAccounts((error,result) => {
        if (error) {
            console.log(error);
        } else {
            callback(result);
        }
    });
}

And then whenever I need the current account I can call it like this:

getAccounts(function(result) {
    console.log(result[0]);
});
| improve this answer | |
  • I'm connecting MM and I'm retrieving all the accounts using web3.eth.getAccounts() as stated in my question. However the first element in the result is not the selected user account, it's just the first account in MM – Veilkrand Jan 17 at 6:54
  • Please a look on this video I just recorded. streamable.com/m8xlx – Miroslav Nedelchev Jan 17 at 7:25
  • I appreciate the effort making the video. Is it possible to handle the account switch event? – Veilkrand Jan 24 at 2:10
  • Sure, you can do it by using this code pastebin.com/cucCmY1v . I also recorded it so you can follow up here streamable.com/3cqy4 . Let me know if you succeed. – Miroslav Nedelchev Jan 24 at 5:21

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.