11

How to check from client-side JavaScript whether MetaMask is installed?

porton
  • 1,774
  • 5
  • 17
  • 38

7 Answers7

8

Not Metamask specifically, but the below checks if Web3 is being injected.

window.addEventListener('load', function() {

  // Check if Web3 has been injected by the browser (Mist/MetaMask).
  if (typeof web3 !== 'undefined') {
    // Use Mist/MetaMask's provider.
    web3js = new Web3(web3.currentProvider);
  } else {
    // Handle the case where the user doesn't have web3. Probably 
    // show them a message telling them to install Metamask in 
    // order to use the app.
  }

});
Richard Horrocks
  • 37,835
  • 13
  • 87
  • 144
6

The recommended way is to use window.ethereum:

window.addEventListener('load', function() {
  if (window.ethereum) {
    console.log('Ethereum support is available')
    if (window.ethereum.isMetaMask) {
      console.log('MetaMask is active')
    } else {
      console.log('MetaMask is not available')
    }
  } else {
    console.log('Ethereum support is not found')
  }
})
Anatoli Babenia
  • 321
  • 2
  • 14
4

MetaMask's own onboarding library runs the test

window.ethereum && window.ethereum.isMetaMask

https://github.com/MetaMask/metamask-onboarding/blob/v1.0.1/src/index.ts#L169

Then create a Provider using new ethers.providers.Web3Provider(window.ethereum)

Luke Hutchison
  • 420
  • 3
  • 11
3
if (typeof window.ethereum !== 'undefined') {
  console.log('MetaMask is installed!');
}

Metamask documentation

MantasFam
  • 327
  • 3
  • 13
1

just 1 line: const isMetamask = ethereum.isMetaMask

it will return true or error.

aakash4dev
  • 691
  • 3
  • 11
1

Just to throw a different solution into the mix, here's a way to check on an interval in case you're up against loading issues. In this example, that interval is every second, it checks 15 times and then gives up.

((context) => {
  const checksBeforeStopping = 15
  let checksMade = 0

const interval = setInterval(() => { if (context?.ethereum?.isMetaMask) { console.log('MetaMask is installed') clearInterval(interval) } else console.log('Will check again in one second')

if (++checksMade === checksBeforeStopping) {
  clearInterval(interval)
  console.log('Giving up on checking for MetaMask')
}

}, 1000) })(window)

1

I found this answer on the Metamask github page https://metamask.github.io/metamask-docs/Advanced_Concepts/Provider_API#ethereum.on(eventname%2C-callback)

if (typeof window.ethereum !== 'undefined'
|| (typeof window.web3 !== 'undefined')) {

  // Web3 browser user detected. You can now use the provider.
  const provider = window['ethereum'] || window.web3.currentProvider
}

Then you call window.ethereum.enable() to request user permission

Barrard
  • 189
  • 2
  • 9