Metamask隐私模式,重要!

当你使用Metamask测试以太坊DApp时,如果出现莫名其妙的问题,检查一下web3.eth.accounts是否可以获取到账户,如果不能获取的话,那么最大的可能是你使用了新版的Metamask,并且默认启用了隐私模式。

有两种办法来让你的DApp可以正常访问Metamask管理的账户:关闭隐私模式,或者修改JavaScript代码使其兼容Metamask的隐私模式。

> 如果希望快速掌握以太坊智能合约与DApp开发,可以访问汇智网的在线互动课程。一、关闭隐私模式

在metamask中首先进入设置,然后点击**security & privacy**,

在隐私模式菜单,选择**关闭隐私模式**即可:

二、兼容隐私模式

在2018年11月,Metamask刚引入隐私模式时,该选项默认是关闭的。但是在

最新的版本中,已经默认开启了隐私模式。要求每个用户都手动关闭隐私模式

是不现实的,因此更好的方案是修改我们的JavaScript代码来兼容隐私模式:

```

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`按钮,你的应用就可以像之前一样访问Metamask的账户了。

发表评论
留言与评论(共有 0 条评论)
   
验证码:

相关文章

推荐文章

'); })();