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"));



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
    Commented May 31, 2017 at 14:45

2 Answers 2


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. Commented May 31, 2017 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
    Commented May 31, 2017 at 14:53
  • Fixed error, accounts. Commented May 31, 2017 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. Commented May 31, 2017 at 14:55
  • @Etherkimist try to define before the Web3 constant o check the callback.
    – Gawey
    Commented May 31, 2017 at 14:57

You can also use await for synchronization.

const getAccount = async () => {
  const accounts = await web3.eth.getAccounts();
  const account = accounts[0];
  return account;

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.