MetaMask Login – How to Check if a User is Logged in to MetaMask

dapp-developmentmetamaskweb3js

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>

Best Answer

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");
});
Related Topic