为何取不到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

相关文章
相关标签/搜索