檢測錢包是否安裝
方法一
// 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 推測可能的提供者。