0

我想通过 web3.js 在我的 metamask 插件中检索当前选择的帐户。而且我想动态地做,所以当切换到另一个帐户时,它应该被打印到 UI 上。

我正在通过以下方式导入库(beta.37): <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.37/dist/web3.min.js"></script>"

让事情变得更复杂:1)在 Braveweb3.eth.accounts[0]中,我会将我的当前地址记录在我的 dApp 以外的任何其他站点中,但在这里,它返回“未定义”。2)在 Chrome(相同版本)中,它总是会返回未定义的。

undefined对我来说,当其他基于 web3.js 0.x 构建的 dApp 使用完全相同的代码时,它如何返回是莫名其妙的。

因此,我不能使用以下函数来动态打印当前地址:

var accountInterval = setInterval(function() {
    if (web3.eth.accounts[0] !== userAccount) {
        userAccount = web3.eth.accounts[0];
    }
}, 100);
4

1 回答 1

2

在 web3.js 1.x 中你必须使用 getAccounts() 异步方法,例如如下:

var accounts = await web3.eth.getAccounts();
var userAccount =accounts[0]

PS:其他 Dapp 中的 web3.eth.accounts[0] 会显示你的账号,因为他们还在使用旧的 web3.js 版本,很可能是 Metamask 注入的那个

于 2019-06-28T12:19:35.207 回答