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

问题描述 投票:0回答:2

我正在使用 web3 进行我的第一次 dapp 测试,我想让 MetaMask 会提示用户将网络更改为 Binance (BSC) 网络(如果尚未选择),就像这里一样:

如何触发这样的请求?

javascript ethereum web3js metamask
2个回答
46
投票

我终于找到答案了:

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

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" 这是因为它不是 rpcUrl,而是字符串数组中的 rpcUrls,还要注意 blockExplorerUrls。

您可以在这里找到metamask的文档

© www.soinside.com 2019 - 2024. All rights reserved.