2

I have searched severally on how to use web3 with metamask without nodejs without any success. I want to be able to get an instance of a user's metamask account through web3 and vanilla javascript without having to go through nodejs and all it's dependencies. I have included web3.mim.js on the head tag and have this code running fine.

window.addEventListener('load', function () {
    if (typeof web3 !== 'undefined') {
        console.log('Web3 Detected! ' + web3.currentProvider.constructor.name);
        window.web3 = new Web3(web3.currentProvider);
    } else {
        console.log('No Web3 Detected... using HTTP Provider')
        window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    }
})

The issue however is that when i try to get default account using web3.eth.defaultAccount i get a null value returned to me. How can i get access to the current account on metamask? I am running the script in an apache server.

1
  • Friend, did you find a solution to this? I need this too right now. Thanks! Commented Oct 1, 2022 at 0:48

1 Answer 1

0

Metamask do not expose the accounts by default anymore. You will need to request the user to allow your app to access the account.

You can use this code (see original post here: https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8 )

window.addEventListener('load', async () => {
    // Modern dapp browsers...
    if (window.ethereum) {
        window.web3 = new Web3(ethereum);
        try {
            // Request account access if needed
            await ethereum.enable();
            // Acccounts now exposed
            web3.eth.sendTransaction({/* ... */});
        } catch (error) {
            // User denied account access...
        }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
        window.web3 = new Web3(web3.currentProvider);
        // Acccounts always exposed
        web3.eth.sendTransaction({/* ... */});
    }
    // Non-dapp browsers...
    else {
        console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
    }
});

If the user has privacy mode anable, when you app loads it will open a metamask window asking to allow connection. If you disable privacy mode it won't ask for anything.

Hope this help.

1
  • @jaime sorry i have a opposite question, how do i Disable/disconnect user if connected? I am required to give user a disconnect button in my dapp. Commented Mar 6, 2021 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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