ethereum - 如何在 MetaMask 上触发更改区 block 链网络请求

标签 ethereum web3 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',
          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');
    } 

关于ethereum - 如何在 MetaMask 上触发更改区 block 链网络请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68252365/

相关文章:

ethereum - Solidity 中的切片数字(例如从 uint 中提取 2 个第一个数字)

ethereum - 如何记录合约自启动以来发出的所有事件?

python - 如何从 web3py 获取事件数据?

node.js - Web3.js 查看方法 call() 错误,因为返回值无效,是否耗尽了气体

ethereum - 从 Metamask 获取所有以太坊账户

ethereum - Solidity 中定点数的求幂(即 a^b)

blockchain - 几天后,私有(private)以太坊区 block 链上的数据丢失/消失

go - 如何从智能合约中转移 ERC20 代币而不转移到基本账户

rust - 如何验证以太坊metamask的签名?