4

I tried a very simple example of web3, it works if you Log In to Metamask and try to send some ETH.

However if I'm not logged in to Metamask no errors and no tips are shown.

How can I check if a user is already logged in to Metamask?

    <html>
      <head>
         <title>Introduction to Dapps. Simple MetaMask example.</title>
      </head>
      <body>
      <div id="meta-mask-required"></div>
      <fieldset>
        <label> Ether:
          <input type="text" id="amount"></input>
        </label>
        <button onclick="send()">Donate to the Author</button>
        <div id="response"></div>
      </fieldset>

      <script>
        // MetaMask injects the web3 library for us.
        window.onload = function() {
          if (typeof web3 === 'undefined') {
            document.getElementById('meta-mask-required').innerHTML = 'You need <a href="https://metamask.io/">MetaMask</a> browser plugin to run this example'
          }
        }
        function send() {
          web3.eth.sendTransaction({
            from: web3.eth.coinbase,
            to: '0xA7b25444868Cc0e6AcFd81852b3bc3F335933760',
            value: web3.toWei(document.getElementById("amount").value, 'ether')
          }, function(error, result) {
            if (!error) {
              document.getElementById('response').innerHTML = 'Success: <a href="https://testnet.etherscan.io/tx/' + result + '"> View Transaction </a>'
            } else {
              document.getElementById('response').innerHTML = '<pre>' + error + '</pre>'
            }
          })
        }
      </script>
      </body>
    </html>
11

The way I solved this is by calling web3.eth.getAccounts()

If it returns an empty array, it in effect means the user is not logged in to MetaMask:

web3.eth.getAccounts(function(err, accounts){
    if (err != null) console.error("An error occurred: "+err);
    else if (accounts.length == 0) console.log("User is not logged in to MetaMask");
    else console.log("User is logged in to MetaMask");
});
| improve this answer | |
  • I did the same thing bug unfortunately, at least as of today, that technique doesn't work. getAccounts() never returns (i.e. - the "then" block attached to the getAccounts() call is never executed). – Robert Oschler Sep 2 '18 at 14:39
  • What about firefox? no web3 in firefox... – Femtosecond May 16 '19 at 6:09

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.