Connecting a simple HTML, CSS, and Javascript frontend to metamask

Connecting a simple HTML, CSS, and Javascript frontend to metamask

Have you ever wondered how to connect a frontend application built with just HTML, CSS, and vanilla Javascript to metamask? If you have, look no further as you are at the right place.

This article aims to explain step by step how to connect a web page to metamask and have your Ethereum account displayed in the browser upon successful connection.

Without further ado, let’s get straight to it.

Prerequisites

In order to follow along with this tutorial, the following technologies are required:

  • HTML (HyperText Markup Language)
  • CSS (Cascading Styles Sheet)
  • Javascript
  • NodeJS (version 16 or higher)
  • Metamask extension
  • Parcel NPM package


  • HTML and CSS are web technologies used for building front-end applications.
  • Javascript is the programming language of browsers, which helps to bring user interactivity to front-end applications.
  • Parcel is a zero-configuration web application bundler with great out-of-the-box support for HTML, CSS, and Javascript and provides a development server.
  • NodeJS, a Javascript runtime is needed to install Parcel through NPM (Node Package Manager). Kindly click this?link?to download it if you have not already.

Project Set Up

First of all, we need to create a folder somewhere in our system where all the code for our project will live.

I have created mine in my Document directory and named it?connect-metamask.?Open the folder in your favorite IDE. I will be using VS Code but feel free to use other alternatives such as Atom, Sublime Text, Bracket, etc.

Then, we have to move into this folder and initialize a new Node project using the command below in the terminal.


npm init -y        

If everything goes well, you should see in your project folder a?package.json?file, which looks something like what is below:


{  
  "name": "connect-metamask",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}        

Next is to install the Parcel package



npm i parcel -D        

This downloads and saves the?parcel?package in your system and will also add it as a dependency in your?package.json?file as shown below


{  
  "name": "connect-metamask",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "parcel": "^2.8.0"
    },
 }        

That is pretty much it in terms of the dependencies for the project. Now let’s get into the folder and file structure.

We will be adopting a simple folder and file structure as this is a simple project. We need to create an?src?folder in the root of the project directory. This is where the majority of our code will live.

No alt text provided for this image
src folder

Above is what the folder structure should look like on your IDE explorer. In the?src?folder, we have to create three files, namely:

  • index.html
  • index.js
  • main.css


main.css

Since the focus of this article is not on CSS, I will just provide the CSS code for the project. Kindly copy and paste the following into your?main.css?file.


body {
  margin: 0;
  height: 100vh;
  display: grid;
  place-content: center;
  background: rgba(0, 0, 0, 0.05);
  font-family: "Nunito";
}

h1 {
  font-size: 2.4rem;
}

.onboard-container {
  box-shadow: 10px 10px 30px rgba(0, 0, 0, 0.1);
  border-radius: 0.7em;
  padding: 4em;
  background: white;
  min-width: 500px;
  text-align: center;
}

.onboard {
  background-color: rgb(76, 0, 255);
  color: white;
  display: inline-block;
  text-decoration: none;
  padding: 0.7em;
  text-align: center;
  font-size: 1.3rem;
  border-radius: 0.3em;
  margin-top: 2em;
}

p {
  font-size: 1.125rem;
}

.loader {
  width: 200px;
  height: 200px;
  margin: 0 auto;
  display: none;
}

.account {
  background: rgb(233, 233, 233);
  padding: 0.3em;
  border-radius: 0.3em;
  position: relative;
  display: inline-block;
  text-indent: 1.2em;
}

.account:before {
  position: absolute;
  content: "";
  background: green;
  width: 0.7em;
  height: 0.7em;
  border-radius: 50%;
  left: 0.5em;
  top: 0.6em;
}

.up {
  position: absolute;
  top: 2em;
  right: 2em;
  width: 10em;
  display: none;
}

.confetti {
  position: absolute;
  width: 20em;
  z-index: 2;
  display: none;
}        

index.html


<!DOCTYPE html
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="./main.css">
    </head>

    <body>
        <div class="onboard-container">
            <div class="loader">
                <lottie-player src="https://assets2.lottiefiles.com/private_files/lf30_lndg7fhf.json"
                    background="transparent" speed="1" loop autoplay></lottie-player>
            </div>
            <div class="up">
                <lottie-player src="https://assets3.lottiefiles.com/packages/lf20_kfzgxkvq.json"
                    background="transparent" speed="1" loop autoplay></lottie-player>
            </div>
            <div class="confetti">
                <lottie-player class="success-anim" src="https://assets10.lottiefiles.com/packages/lf20_rovf9gzu.json"
                    background="transparent" speed="1"></lottie-player>
            </div>
            <h1></h1>
            <p class="desc"></p>
            <a href="#" class="onboard"></a>
        </div>
        <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
        <script src="./index.js" type="module"></script>
    </body>

</html>>        

You may have already noticed a?lottie-player?HTML element above. It is a special HTML element we will be using to implement some cool animations.

Also, notice the?main.css?and the?index.js?files are already linked in the HTML file with the script?lottie-player?URL also added.

index.js

This is where most of the magic happens.

The first set of things to do is to grab a reference to a number of the HTML elements like so:


const player = document.querySelector(".success-anim")
const btn = document.querySelector(".onboard");
const statusText = document.querySelector("h1");
const statusDesc = document.querySelector(".desc");
const loader = document.querySelector(".loader");
const upArrow = document.querySelector(".up");
const confetti = document.querySelector(".confetti");        

We then need a function (say?isMetaMaskInstalled) to determine whether or not the metamask extension is installed in the user’s browser.


const isMetaMaskInstalled = () => 
  const { ethereum } = window;
  return Boolean(ethereum && ethereum.isMetaMask);
};{        

With the above function, we can get the application to send appropriate feedback to a user who has not installed the metamask extension yet.

At this point, we have to implement a function to help instruct the user exactly what actions to take based on whether he/she has metamask installed.


const MetaMaskClientCheck = () => 
  if (!isMetaMaskInstalled()) {
    statusText.innerText = "You need to Install a Wallet";
    statusDesc.innerText = "We recommend the MetaMask wallet.";
    btn.innerText = "Install MetaMask";
  } else {
    connectWallet().then((accounts) => {
      if (accounts && accounts[0] > 0) {
        showAddress(accounts);
      } else {
        statusText.innerHTML = "Connect your wallet";
        statusDesc.innerHTML = `To begin, please connect your MetaMask wallet.`;
        btn.innerText = "Connect MetaMask";
        upArrow.style.display = "block";
      }
    });
  }
};{        

Notice two functions we are calling but have not implemented yet —?connectWallet?and?showAddress.?So let us fix that.


async function connectWallet() 
  return await ethereum.request({ method: "eth_accounts" });
}

let showAddress = (accounts) => {
  statusText.innerHTML = "Connected!";
  statusDesc.classList.add("account");
  statusDesc.innerHTML = accounts[0];
  btn.style.display = "none";
  loader.style.display = "none";
  upArrow.style.display = "none";
  confetti.style.display = "block";
  player.play();
  statusDesc.classList.add("account");
};{        

connectWallet?leverages the Ethereum object to get the user’s accounts while?showAddress?updates the UI accordingly.

The last step will be to add a click event listener to the HTML element with a class of?btn?so that upon clicking, it redirects the user to metamask page to have his/her account connected to the application.


btn.addEventListener("click", async () => 
  btn.style.backgroundColor = "#cccccc";
  loader.style.display = "block";

  try {
    const accounts = await ethereum.request({ method: "eth_requestAccounts" });
    showAddress(accounts);
  } catch (error) {
    console.error(error);
  }
});{        

It is time for the moment of truth??

We first have to update the scripts in the?package.json?file as follows:


{
  "name": "connect-metamask",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "parcel",
    "build": "parcel build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",

  "devDependencies": {
    "parcel": "^2.8.0"
  }
}        

Now, in order to open the application in the browser, run the following command in the terminal from the root project directory.


npx parcel src/index.html         

This should spin up the development server?Parcel?provides at?https://localhost:1234

Navigating to the URL, you should see a screen like below:

No alt text provided for this image

Meanwhile, if you do not have metamask installed in your browser, you would see a screen like below:

No alt text provided for this image

Now, click the?Connect Metamask?button and you should be presented with the below screen:

No alt text provided for this image

Upon clicking the next and connect button, you should see your Ethereum account displayed in the browser like so

No alt text provided for this image

If you made it to this point, congratulations??

You have just built a simple front-end application that connects to the metamask wallet.

That’s it, guys. Click?here?to see the source code on GitHub.

Thanks for reading and please feel free to leave comments.

References

LUCAS MOREIRA DE SOUSA

Líder de rede na CGMAX - Central Gospel MAX

1 年
回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了