【web3】
检测钱包是否安装
方法一
// npm install @metamask/detect-provider
import detectEthereumProvider from '@metamask/detect-provider'
// 检测钱包是否安装
const isProvider = await detectEthereumProvider()
if(!isProvider) {
proxy.$modal.msgError("请安装钱包");
return
}
方法二
async function detectWallet() {
try {
// 检查浏览器是否支持以太坊钱包,如果没有检测到window.ethereum,意味着没有钱包扩展被安装
if(typeof window.ethereum == "undefined") {
proxy.$modal.msgError("请安装钱包");
return
}
const isProvider = window.ethereum
// 检测安装的钱包
if(isProvider.isMetaMask) {
console.log("MetaMask 钱包");
}
if (isProvider.isTokenPocket) {
console.log("TokenPocket 钱包");
} else {
console.log("其他以太坊兼容钱包");
}
} catch (e) {
console.log(e)
}
}
window.ethereum 是浏览器中的以太坊提供者对象,它提供了与区块链交互的功能(例如发送交易,查询余额等)。
注意事项
安装 TP 钱包时,isProvider.isMetaMask 返回也是true,因为 window.ethereum 对象的 isMetaMask 属性并非专门区分不同钱包提供者的标识。很多以太坊兼容钱包会模仿 MetaMask 的行为,在 window.ethereum对象上设置类似的表示,以便兼容现有的 Web3 代码库,因此 isMetaMask 属性不能准确反映当前的钱包类型。
如果想解决这个问题,可以尝试检查其它钱包特定标识符(如 isTokenPocket),或者使用更复杂的逻辑来区分不同的以太坊兼容钱包。
或者通过 ethereum.chainId 区分钱包:window.ethereum.chainId 来查看当前连接的链 ID,然后根据链 ID 推测可能的提供者。