Connecting with Ether Js
using ether js to connect to your Metamask Wallet.
Ether Js
using HTML, Javascript & Ether Js to enter into the Web 3 world.
connectwallet.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MetaMask Connection and Balance Example</title>
<!-- Check if MetaMask is installed -->
<script>
window.addEventListener('DOMContentLoaded', () => {
if (typeof window.ethereum === 'undefined') {
alert('MetaMask not detected! Please install MetaMask.');
}
});
</script>
<!-- Include ethers.js script -->
<script src="https://cdn.ethers.io/lib/ethers-5.0.umd.min.js"></script>
</head>
<body>
<button id="connectButton">Connect to MetaMask</button>
<div id="result"></div>
<script>
document.getElementById('connectButton').addEventListener('click', async () => {
try {
// Check if MetaMask is installed
if (typeof window.ethereum === 'undefined') {
alert('MetaMask not detected! Please install MetaMask.');
return;
}
// Request permission to connect MetaMask account
await ethereum.request({ method: 'eth_requestAccounts' });
// Create a Web3Provider using MetaMask's provider
const provider = new ethers.providers.Web3Provider(window.ethereum);
// Get the account signer
const signer = provider.getSigner();
// Get the current block number
const blockNumber = await provider.getBlockNumber();
// Get the balance of the connected account
const address = await signer.getAddress();
const balance = await provider.getBalance(address);
const formattedBalance = ethers.utils.formatEther(balance);
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = `
`;
} catch (error) {
console.error('Error connecting to MetaMask:', error);
alert('Error connecting to MetaMask. Check the console for details.');
}
});
</script>
</body>
</html>
Feel free to play around and edit this post as much you like.
Learn more on how to query the blockchain using EtherJs.