7

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?

2 Answers 2

3
async function onInit() {
        await window.ethereum.enable();
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
        const account = accounts[0];
        console.log(account)
         window.ethereum.on('accountsChanged', function (accounts) {
            // Time to reload your interface with accounts[0]!
            console.log(accounts[0])
           });
    }

    onInit();

try this!!

4

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]);
});
5
  • 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, 2020 at 6:54
  • Please a look on this video I just recorded. streamable.com/m8xlx Jan 17, 2020 at 7:25
  • I appreciate the effort making the video. Is it possible to handle the account switch event?
    – Veilkrand
    Jan 24, 2020 at 2:10
  • 1
    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. Jan 24, 2020 at 5:21
  • This the first account right? Not the current account.
    – GN.
    Dec 13, 2020 at 7:15

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.