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

问题描述

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

metamask requesto change network

如何触发这样的请求?

解决方法

我终于找到了答案:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...