当你使用Metamask测试以太坊DApp时,如果出现莫名其妙的问题,检查一下web3.eth.accounts是否可以获取到账户,如果不能获取的话,那么最大的可能是你使用了新版的Metamask,并且默认启用了隐私模式。
有两种办法来让你的DApp可以正常访问Metamask管理的账户:关闭隐私模式,或者修改代码使其兼容隐私模式。
一、关闭隐私模式
在metamask中首先进入设置,然后点击security & privacy,在隐私模式菜单,选择关闭隐私模式即可:
![11831773-a0b82ec7217b061d.png](https://i-blog.csdnimg.cn/blog_migrate/7157c1d833ca0b9c031c62db140cc632.webp?x-image-process=image/format,png)
menu 2
二、兼容隐私模式
在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 ac