如何在MetaMask上触发更改区块链网络请求

20
我正在使用web3进行我的第一个dapp测试,我希望MetaMask会提示用户切换网络到币安(BSC)网络,如果尚未选择的话,就像这里一样。

metamask requesto change network

如何触发这样的请求?
2个回答

48
我终于找到了答案:

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

更全面的答案需要检查MetaMask是否已安装,以及该软件是否安装了您的Dapp想要连接到的链,如果没有安装它:

 // 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');
    } 

1
谢谢,我一直在寻找如何更改它的方法,但是一直没有头绪,最后我找到了你的答案。 - Armin Eslami

6
async switchEthereumChain() {
    try {
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: '0x61' }],
      });
    } catch (e: any) {
      if (e.code === 4902) {
        try {
          await window.ethereum.request({
            method: 'wallet_addEthereumChain',
            params: [
              {
                chainId: '0x61',
                chainName: 'Smart Chain - Testnet',
                nativeCurrency: {
                  name: 'Binance',
                  symbol: 'BNB', // 2-6 characters long
                  decimals: 18
                },
                blockExplorerUrls: ['https://testnet.bscscan.com'],
                rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545/'],
              },
            ],
          });
        } catch (addError) {
          console.error(addError);
        }
      }
      // console.error(e)
    }
  }

尽管上述答案对我无效,但它给了我一个错误的提示:不支持的键:rpcUrl,这是因为应该把rpcUrls作为字符串数组中的一个元素,同时注意blockExplorerUrls。
您可以在此处找到metamask的文档here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接