【问题标题】:Issue with getting web3.eth.accounts (MetaMask)获取 web3.eth.accounts (MetaMask) 的问题
【发布时间】:2018-07-06 14:20:06
【问题描述】:

我的 MetaMask 已启用,但在控制台中我看到空数组 image here,当我尝试 console.log(web3.eth.accounts[0]) 时,它返回 undefined

但是当我使用console.log(web3.eth) 时,我会在控制台中看到所有数据image here

有人知道为什么web3.eth.accounts[0]web3.eth.accounts 不起作用吗?

<html>
    <head>
        <title>TEST</title>
    </head>
    <body>
        <script>
            window.addEventListener('load', function(){
                if( typeof web3 !='undefined'){
                    console.log('web3 detected');
                    web3 = new Web3(web3.currentProvider);                                    
                    console.log(web3.eth.accounts);
                }else{
                    alert("please install MetaMask");
                }
            });
                       
        </script>
    </body>
</html>

【问题讨论】:

    标签: javascript ethereum web3js web3 metamask


    【解决方案1】:

    我解决了问题,使用:

     web3.eth.getAccounts((err, res) => {                   
                       console.log(res[0]);
    });
    

    但无论如何,问题仍然存在,为什么 web3.eth.accounts[0] 不起作用?

    【讨论】:

    • 它不起作用,因为它不是您期望的帐户列表。它是您可以使用的整个包的构造函数。查看docs了解更多详情
    【解决方案2】:

    要获取当前连接的帐户,您需要编写,

    const web3 = new Web3(window.ethereum);
    web3.eth.requestAccounts().then(accounts => console.log(accounts));
    

    【讨论】:

      【解决方案3】:

      web3.eth.accounts[0] 不起作用,因为web3.eth.accounts 不是帐户列表,正如docs 中所说:

      像这样获取帐户:

      var account = null;
      web3.eth.getAccounts(async function(error, accounts) {
        if (error == null && accounts.length > 0) {
            account = accounts[0];
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-05-24
        • 2018-05-04
        • 2018-02-19
        • 2018-11-04
        • 1970-01-01
        • 2021-06-29
        • 2020-08-30
        • 1970-01-01
        • 2022-06-24
        相关资源
        最近更新 更多