HTML code that includes a function to connect and switch between multiple networks like Polygon and Optimism using separate buttons.
This is a function in HTML that allows users to connect and switch between multiple networks like Polygon and Optimism using separate buttons. The code utilizes web3 and Metamask to handle the network connections. By clicking on the respective buttons, users can connect to the desired network. The function checks if Metamask is installed and connected before switching to the specified network. If the network is already selected, it displays a message indicating that the user is already connected to that network. If there are any errors during the connection process, appropriate error messages are displayed. Please note that this code assumes the presence of the web3 library and Metamask extension.
<!DOCTYPE html>
<html>
<head>
<title>Web3 Metamask Network Switcher</title>
</head>
<body>
<h1>Web3 Metamask Network Switcher</h1>
<button onclick="connectToPolygon()">Connect to Polygon</button>
<button onclick="connectToOptimism()">Connect to Optimism</button>
<script src="https://cdn.jsdelivr.net/npm/web3/dist/web3.min.js"></script>
<script>
/**
* @function connectToPolygon
* @description Connects to the Polygon network using Web3 and Metamask.
*/
function connectToPolygon() {
// Check if Metamask is installed
if (typeof window.ethereum === 'undefined') {
console.error('Metamask is not installed.');
return;
}
// Check if Metamask is connected
if (!window.ethereum.isConnected()) {
console.error('Metamask is not connected.');
return;
}
// Check if Polygon network is already selected
if (window.ethereum.networkVersion === '137') {
console.log('Already connected to Polygon network.');
return;
}
// Switch to Polygon network
window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0x89' }],
})
.then(() => {
console.log('Connected to Polygon network.');
})
.catch((error) => {
console.error('Failed to connect to Polygon network:', error);
});
}
/**
* @function connectToOptimism
* @description Connects to the Optimism network using Web3 and Metamask.
*/
function connectToOptimism() {
// Check if Metamask is installed
if (typeof window.ethereum === 'undefined') {
console.error('Metamask is not installed.');
return;
}
// Check if Metamask is connected
if (!window.ethereum.isConnected()) {
console.error('Metamask is not connected.');
return;
}
// Check if Optimism network is already selected
if (window.ethereum.networkVersion === '10') {
console.log('Already connected to Optimism network.');
return;
}
// Switch to Optimism network
window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0xA869' }],
})
.then(() => {
console.log('Connected to Optimism network.');
})
.catch((error) => {
console.error('Failed to connect to Optimism network:', error);
});
}
</script>
</body>
</html>