ethereum - 如何在 MetaMask 上触发更改区块链网络请求
问题描述
我正在使用 web3 进行我的第一个 dapp 测试,我想这样做 MetaMask 将提示用户将网络更改为 Binance (BSC) 网络(如果尚未选择),就像这里一样:
如何触发这样的请求?
解决方案
我终于找到了答案:
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');
}
推荐阅读
- mysql - 使用 MySQL 5.7 for MySQL Aurora 在不同区域之间快速迁移 RDS
- javascript - 使用 JavaScript 的字符串填充中心
- python - 使用 google colab 读取 Google 驱动文件时出现输入/输出错误
- telegram - 如何在不使用 /getUpdates 的情况下知道 Telegram 上群组的聊天 ID?
- java - 如何在 LinkedList 上正确同步?
- tensorflow - 输入类型为字符串的 tensorflow savedModel 预测时收到“Tensor Placeholder”错误
- vue.js - 设置后立即使用 Vuex 数据
- python - Python中的AP使用函数
- php - 如何在 Stripe 中更改语言 - Woocommerce
- reactjs - 如何从 redux 状态更新我的反应