How to check from client-side JavaScript whether MetaMask is installed?
7 Answers
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.
}
});
- 37,835
- 13
- 87
- 144
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')
}
})
- 321
- 2
- 14
-
1github link is dead – alper May 09 '22 at 19:56
-
@alper fixed the link and updated code. Let me know if it works. – Anatoli Babenia Feb 07 '23 at 10:33
-
1it works, thanks – alper Feb 08 '23 at 22:05
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)
- 420
- 3
- 11
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask is installed!');
}
- 327
- 3
- 13
just 1 line:
const isMetamask = ethereum.isMetaMask
it will return true or error.
- 691
- 3
- 11
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)
- 111
- 2
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
- 189
- 2
- 9
-
-
I think this is the correct link: https://docs.metamask.io/guide/getting-started.html#basic-considerations – MantasFam Mar 03 '22 at 09:46
-
1
window['ethereum']is not a provider. You have to create a provider from this:new ethers.providers.Web3Provider(window.ethereum)– Luke Hutchison Jul 31 '22 at 02:46