web3.js – Using Vanilla JavaScript with web3 and Metamask

javascriptmetamasknodejsweb3js

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.

Best Answer

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.

Related Topic