Web3.js MetaMask – How to Get the Current User Account Selected

metamaskweb3js

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?

Best Answer

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!!

Related Topic