Web3.eth.getAccounts get account address is empty solution

It can be obtained in the old version of MetaMask, because the account address is public by default. MetaMask has been updated after November 2, 2018. By default, no account address is disclosed, so to obtain the account address, you must first request user authorization . MetaMask Major Update Documentation

 

 

 Mainly improve the example code of creating  web3 a little bit and ask for user authorization , just upload the source code directly

 

Note: web3.js version is 0.2.0

 

 /* 新版的方式 */
  var web3Provider;
  if (window.ethereum) {
    web3Provider = window.ethereum;
    try {
      // 请求用户授权
      await window.ethereum.enable();
    } catch (error) {
      // 用户不授权时
      console.error("User denied account access")
    }
  } else if (window.web3) {   // 老版 MetaMask Legacy dapp browsers...
    web3Provider = window.web3.currentProvider;
  } else {
    web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
  }
  web3js = new Web3(web3Provider);//web3js就是你需要的web3实例

  web3js.eth.getAccounts(function (error, result) {
    if (!error)
      console.log(result)//授权成功后result能正常获取到账号了
  });

 

Guess you like

Origin blog.csdn.net/weixin_36941283/article/details/103778439