一個教做網(wǎng)頁的網(wǎng)站網(wǎng)站如何推廣運營
detect-metamask
創(chuàng)建連接,并監(jiān)聽錢包切換
一、連接錢包,切換地址(監(jiān)聽地址切換),斷開連接
- 使用npm安裝 @metamask/detect-provider在您的項目目錄中:
npm i @metamask/detect-provider
import detectEthereumProvider from "@metamask/detect-provider";
async onLoad() {if (typeof window.ethereum !== "undefined") {console.log("MetaMask 已安裝!");}this.provider = await detectEthereumProvider();this.provider.request({method: "eth_accounts"}).then(this.handleAccountsChanged).catch((err) => {console.error(err);});this.provider.on("accountsChanged", this.handleAccountsChanged);
},
methods: {// 這個方法,只在錢包APP內(nèi)可以監(jiān)聽到地址切換,瀏覽器不行。handleAccountsChanged(accounts) {console.log('監(jiān)聽', accounts);if (accounts.length === 0) {console.log("請連接到MetaMask");} else if (accounts[0] !== this.address) {console.log('地址發(fā)生更換', this.address);this.address = accounts[0];}},// 連接錢包async getAccount() {// 1.向用戶請求連接錢包,彈出錢包選擇賬戶let res = await window.ethereum.request({"method": "wallet_requestPermissions","params": [{"eth_accounts": {}}]}).catch((err) => {// User rejected the request. (用戶拒絕了請求。)console.log(err.message);});if(res){// 2.選擇地址并確認(rèn)let accounts = await this.provider.request({method: "eth_requestAccounts"}).catch((err) => {if (err.code === 4001) {console.log("請連接到MetaMask.");} else {console.error(err);}});this.address = accounts[0]; // 當(dāng)前錢包地址}},// 關(guān)閉連接,僅適用于瀏覽器擴展。async closeAccount() {var res = await window.ethereum.request({"method": "wallet_revokePermissions","params": [{"eth_accounts": {}}]});this.address = ''console.log('連接已斷開', res);},
}
實現(xiàn)的效果圖: