How to connect a MetaMask wallet to your website with vanilla JavaScript
In this guide, we're going to learn how to use the web3 library with vanilla JavaScript and how you can connect a MetaMask wallet to your website.
To be able to interact with the Ethereum network easily, the best solution is to use the Web3js library.
In this guide, we're going to learn how to use the web3
library with vanilla JavaScript and how you can connect a MetaMask wallet to your website.
The first thing you need is to include the library to your code. With vanilla JavaScript, it is easier for you to not use a package manager like npm
or yarn
.
Instead, we are going to use a CDN. If you go to the Github repository of the library: https://github.com/ChainSafe/web3.js/tree/v1.4.0
You can see that they give you 2 scripts to include in the head
of your HTML file. You can use either one of them, they are equivalent.
So the first thing you need to do is to copy and paste one of the scripts to include the library to your project:
...
<head>
...
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
</head>
...
After that, you will have access to everything in the library under the Web3
variable.
Now, to start using the web3 library, all you need to do is pass a provider to that Web3
object. In our case, since you want to connect to the user's wallet, the wallet will be our provider. Otherwise, you can use blockchain APIs like Infura or QuickNodes.
To connect a MetaMask wallet to your website, use this code:
if (window.ethereum) {
const accounts = await window.ethereum.request({method: 'eth_requestAccounts'});
const account = accounts[0]
const web3 = new Web3(window.ethereum);
}
If window.ethereum
is set, then it means that the MetaMask extension is installed in the browser so you can connect to it and use it as a provider for the web3
.
The line after the if
statement asks the user to connect his wallet. This will show a pop-up to the user on his MetaMask wallet and ask if he accepts to connect to your website.
If the user accepts, then you can access his address just like what we're doing with the account
variable.
If the user accepts, then you can also start using his wallet as a provider to interact with the blockchain just like what we're doing with the web3
variable.
That way, every time you want to fire a transaction using the user's account, a pop-up will appear in the wallet to ask the user if he accepts firing that transaction or not.
Feel free to read the documentation and our other articles to learn how to use the web3js library!
Thanks for reading this post!