Skip to content

Instantly share code, notes, and snippets.

@spapas
Created February 1, 2022 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spapas/73eec2c50aa7f32d94e0b85c8782a665 to your computer and use it in GitHub Desktop.
Save spapas/73eec2c50aa7f32d94e0b85c8782a665 to your computer and use it in GitHub Desktop.
Connect to metamask using only the ethereum API (not deps)
<!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