Created
February 1, 2022 10:06
-
-
Save spapas/73eec2c50aa7f32d94e0b85c8782a665 to your computer and use it in GitHub Desktop.
Connect to metamask using only the ethereum API (not deps)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>WEB3</title> | |
</head> | |
<body> | |
<button id='connectButton'>Connect to metamask</button> | |
<script> | |
let chainId = null; | |
let currentAccount = null; | |
ethereum.request({ method: 'eth_chainId' }).then(function (_chainId) { | |
chainId = _chainId; | |
console.log('Chain ID:', chainId); | |
}) | |
ethereum.on('chainChanged', handleChainChanged); | |
function handleChainChanged(_chainId) { | |
console.log('Chain ID CHANGED:', chainId); | |
} | |
ethereum | |
.request({ method: 'eth_accounts' }) | |
.then(handleAccountsChanged) | |
.catch((err) => { | |
console.error(err); | |
}); | |
ethereum.on('accountsChanged', handleAccountsChanged); | |
function handleAccountsChanged(accounts) { | |
if (accounts.length === 0) { | |
console.log('Please connect to MetaMask.'); | |
} else if (accounts[0] !== currentAccount) { | |
currentAccount = accounts[0]; | |
console.log("Connected with: " + currentAccount) | |
} | |
} | |
document.getElementById('connectButton').onclick = connect; | |
function connect() { | |
ethereum | |
.request({ method: 'eth_requestAccounts' }) | |
.then(handleAccountsChanged) | |
.catch((err) => { | |
if (err.code === 4001) { | |
console.log('Please connect to MetaMask.'); | |
} else { | |
console.error(err); | |
} | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment