6

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>

3 Answers 3

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");
});
3
  • 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). Commented Sep 2, 2018 at 14:39
  • What about firefox? no web3 in firefox... Commented May 16, 2019 at 6:09
  • Note getAccounts is deprecated in favour of an eth_accounts RPC Commented Jun 28, 2021 at 12:11
5

MetaMask will no longer be injecting web3, so it's not good practice to rely on it.

I used the ethers.js library. I had to pull that in to my project using rollup.js, but you could also use bundler or webpack or whatever.

const { ethereum } = window;
if (ethereum) {
    var provider = new ethers.providers.Web3Provider(ethereum);
}

...

const isMetaMaskConnected = async () => {
    const accounts = await provider.listAccounts();
    return accounts.length > 0;
}

await isMetaMaskConnected().then((connected) => {
    if (connected) {
        // metamask is connected
    } else {
        // metamask is not connected
    }
});
0

I think you can use the Provider and see how many accounts you have and from there if you have 0 accounts you can think that the user has not connected any account. Take account this example:

function handleAccountsChanged(accounts) {
  if (accounts.length === 0) {
   // MetaMask is locked or the user has not connected any accounts
   console.log('Please connect to MetaMask.');
  } else if (accounts[0] !== currentAccount) {
    currentAccount = accounts[0];
    // Do any other work!
  }
}

You can see more complete info as an example here: https://docs.metamask.io/guide/ethereum-provider.html#using-the-provider

3
  • 1
    Careful! As stated in the documentation, "connected" and "disconnected" refer to whether the provider can make RPC requests to the current chain, but has nothing to do whether the user is already logged in to Metamask Commented Mar 12, 2021 at 3:38
  • it's removed already. Commented Jun 7, 2021 at 10:53
  • @SergiJuanati you 100% correct thanks for the comment here !. I will update this ! Commented Jun 7, 2021 at 17:20

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.