6

I am facing some problem with metamask. I ve copied the code below from the metamask documentation to load the web3 but i get always web3.eth.accounts[0] returns undefined when i try to get the account's address even if metamask is connected to ropsten. The same code works with Mist perfectly.

window.addEventListener('load', function() {

    if (typeof web3 !== 'undefined') {
        // Use Mist/MetaMask's provider
        window.web3 = new Web3(web3.currentProvider);
        console.log("Metamask used");
    } else {
        console.log('No web3? You should consider trying MetaMask!')
        // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
        window.web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/token"));
    }

    console.log('test1'+web3.eth.accounts[0]);

});
console.log('test'+web3.eth.accounts[0]);

i get the output of the first log.

  • this is your code? maybe is a problem of the asynchronous system... Are you using well the callback function :/ ? – Gawey May 31 '17 at 14:45
11

Metamask does not let you use synchronous functions. Use instead:

web3.eth.getAccounts(function(error, accounts) {
    ...
});

And remove your second log. You only want to do things after you have properly initialised.

  • Thank you but i think it is a loading issue, because after some refresh it returns the address. – Etherkimist May 31 '17 at 14:52
  • 1
    don't go first error and not accounts? :/ web3.eth.getBlock(48, function(error, result){ if(!error) console.log(result) else console.error(error); }) – Gawey May 31 '17 at 14:53
  • Fixed error, accounts. – Xavier Leprêtre B9lab May 31 '17 at 14:54
  • If after some refresh it works, it is more likely that it works by a quirk of the refresh. It should work at the first go. – Xavier Leprêtre B9lab May 31 '17 at 14:55
  • @Etherkimist try to define before the Web3 constant o check the callback. – Gawey May 31 '17 at 14:57

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.