Skip to content

Commit

Permalink
Update 4.html
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasBlock authored Apr 28, 2024
1 parent 111dee5 commit ccf2980
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions 4.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,31 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MetaMask Chain Switch</title>
<script>
const provider = window.ethereum;
document.addEventListener('DOMContentLoaded', function () {
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask is installed!');
} else {
alert("Please install MetaMask!");
}
});

async function switchChain(chainId, chainName, rpcUrl, explorer, currencySymbol) {
if (!provider) {
alert("MetaMask is not installed!");
if (!window.ethereum) {
alert("MetaMask is not available!");
return;
}

const hexChainId = '0x' + chainId.toString(16); // Convert decimal to hexadecimal for MetaMask compatibility

try {
await provider.request({
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: hexChainId }]
});
} catch (switchError) {
console.error(switchError);
if (switchError.code === 4902) {
addChain(chainId, chainName, rpcUrl, explorer, currencySymbol);
await addChain(chainId, chainName, rpcUrl, explorer, currencySymbol);
} else {
console.error("Unable to switch to the chain.");
}
Expand All @@ -34,7 +40,7 @@
const hexChainId = '0x' + chainId.toString(16); // Ensure chain ID is in hexadecimal

try {
await provider.request({
await window.ethereum.request({
method: "wallet_addEthereumChain",
params: [{
chainId: hexChainId,
Expand Down

0 comments on commit ccf2980

Please sign in to comment.