首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >‘web3.currentProvider’是用MetaMask未定义的

‘web3.currentProvider’是用MetaMask未定义的
EN

Ethereum用户
提问于 2017-12-05 20:09:12
回答 2查看 11.8K关注 0票数 1

我正在尝试使用web3.js为我的合同开发一个简单的UI,但我比较早:定义了web3 (和window.web3),但currentProvider属性没有定义。

代码语言:javascript
运行
复制
var Web3 = require('web3');
var web3 = new Web3();

function init() {
  if (typeof web3 !== 'undefined') {
    console.log('Web3 found');
    window.web3 = new Web3(web3.currentProvider);
    web3.eth.defaultAccount = web3.eth.accounts[0];
  } else {
     console.error('web3 was undefined');
  }
}

我试图使用的代码是在上面提供的,并且不包含额外的库或依赖项(如ethjs)。init函数与window.onload事件一起调用。

我做错什么了吗?

EN

回答 2

Ethereum用户

回答已采纳

发布于 2017-12-05 21:55:45

var web3 = new Web3();覆盖由MetaMask注入的web3提供程序。因此,定义了web3,但没有定义currentProvider。如果你把这一行换成

代码语言:javascript
运行
复制
var web3;

您的代码从上面将起作用。

票数 3
EN

Ethereum用户

发布于 2019-03-02 20:17:32

web3 1.0.0 beta的一种建议方法是:

代码语言:javascript
运行
复制
if ((typeof window.ethereum !== 'undefined')
    || (typeof window.web3 !== 'undefined')) {
        return new Web3(window['ethereum'] || window.web3.currentProvider)
    } else {
        // here you could use a different provider, maybe use an infura account, or maybe let the user know that they need to install metamask in order to continue
        return new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/..."))
}

https://metamask.github.io/metamask-docs/Advanced_Concepts/Provider_API

票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/32551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档