爲何取不到metamask的帳號?

當你使用Metamask測試以太坊DApp時,若是出現莫名其妙的問題,檢查一下web3.eth.accounts是否能夠獲取到帳戶,若是不能獲取的話,那麼最大的多是你使用了新版的Metamask,而且默認啓用了隱私模式。web

有兩種辦法來讓你的DApp能夠正常訪問Metamask管理的帳戶:關閉隱私模式,或者修改JavaScript代碼使其兼容Metamask的隱私模式。app

1、關閉隱私模式

在metamask中首先進入設置,而後點擊security & privacy, 在隱私模式菜單,選擇關閉隱私模式便可:async

menu 2

2、兼容隱私模式

在2018年11月,Metamask剛引入隱私模式時,該選項默認是關閉的。可是在 最新的版本中,已經默認開啓了隱私模式。要求每一個用戶都手動關閉隱私模式 是不現實的,所以更好的方案是修改咱們的JavaScript代碼來兼容隱私模式:ide

window.addEventListener('load', async () => {
    // Modern dapp browsers...
    if (window.ethereum) {
        window.web3 = new Web3(ethereum);
        try {
            // Request account access if needed
            await ethereum.enable();
            // Acccounts now exposed
            web3.eth.sendTransaction({/* ... */});
        } catch (error) {
            // User denied account access...
        }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
        window.web3 = new Web3(web3.currentProvider);
        // Acccounts always exposed
        web3.eth.sendTransaction({/* ... */});
    }
    // Non-dapp browsers...
    else {
        console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
    }
});

使用window.ethereum來判斷是否新版metamask,若是是的話,就調用ethereum.enable() 方法來請求用戶受權,這將在用戶網頁中彈出一個受權對話框,相似以下:測試

connect request

一旦用戶點擊了connect按鈕,你的應用就能夠像以前同樣訪問Metamask的帳戶了。3d

若是但願快速掌握以太坊智能合約與DApp開發,能夠訪問匯智網的在線互動課程:code


原文連接:Metamask不能訪問帳戶?隱私模式! — 匯智網blog

相關文章
相關標籤/搜索