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?

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

        // 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() {
            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>'

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

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

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.