javascriptethereumweb3jsmetamask

How to trigger change blockchain network request on MetaMask


I am using web3 for my first dapp test and I'd like to make so MetaMask will prompt the user to change the network to Binance (BSC) network if it is not selected already, just like here:

metamask requesto change network

How to trigger such a request?


Solution

  • I was finally able to find the answer:

    await window.ethereum.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: '0x61' }], // chainId must be in hexadecimal numbers
    });
    

    A more comprehensive answer would check if MetaMask is installed and if this one has installed the chain your Dapp wants to connect to, and if it is not install it:

     // Check if MetaMask is installed
     // MetaMask injects the global API into window.ethereum
     if (window.ethereum) {
          try {
            // check if the chain to connect to is installed
            await window.ethereum.request({
              method: 'wallet_switchEthereumChain',
              params: [{ chainId: '0x61' }], // chainId must be in hexadecimal numbers
            });
          } catch (error) {
            // This error code indicates that the chain has not been added to MetaMask
            // if it is not, then install it into the user MetaMask
            if (error.code === 4902) {
              try {
                await window.ethereum.request({
                  method: 'wallet_addEthereumChain',
                  params: [
                    {
                      chainId: '0x61',
                      rpcUrl: 'https://data-seed-prebsc-1-s1.binance.org:8545/',
                    },
                  ],
                });
              } catch (addError) {
                console.error(addError);
              }
            }
            console.error(error);
          }
        } else {
          // if no window.ethereum then MetaMask is not installed
          alert('MetaMask is not installed. Please consider installing it: https://metamask.io/download.html');
        }