MetaMask is a popular cryptocurrency wallet that allows users to interact with decentralized applications (DApps) on the Ethereum blockchain. This guide will walk you through the steps to connect MetaMask to your DApp.

Prerequisites

  • MetaMask installed in your browser.
  • A basic understanding of HTML, JavaScript, and Ethereum.

Step 1: Setting Up Your HTML File

Start by creating a simple HTML file that will serve as the frontend for your DApp. Below is a basic structure:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Connect MetaMask</title>
</head>
<body>
<h1>Connect to MetaMask</h1>
<button id="connectButton">Connect Wallet</button>
<h2>Account: <span id="account"></span></h2>
<script src="https://cdn.jsdelivr.net/npm/web3/dist/web3.min.js"></script>
<script src="app.js"></script>
</body>
</html>

Step 2: Writing the JavaScript Code

Create a JavaScript file named app.js to handle the connection to MetaMask. Below is a sample code snippet:


const connectButton = document.getElementById('connectButton');
const accountDisplay = document.getElementById('account');

connectButton.addEventListener('click', async () => {
if (typeof window.ethereum !== 'undefined') {
try {
// Request account access
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
accountDisplay.innerText = accounts[0];
} catch (error) {
console.error("User denied account access", error);
}
} else {
console.log('MetaMask is not installed. Please install it to use this DApp.');
}
});

Step 3: Running Your DApp

To run your DApp, you can use a simple local server. If you have Node.js installed, you can use lite-server:


npm install -g lite-server
lite-server

Your DApp will be available at http://127.0.0.1:3000/.

Conclusion

By following these steps, you can successfully connect MetaMask to your DApp. This allows users to interact with your application securely and efficiently. As you develop your DApp further, consider exploring additional features such as network switching and transaction handling.