作者:mobiledu2502937927 | 来源:互联网 | 2022-12-28 15:50
我试图在React js app中使用MetaMask中的web3,如下所示:
import Web3 from 'web3';
componentDidMount(){
if (typeof web3 !== 'undefined') {
console.log(web3.currentProvider);
// Use Mist/MetaMask's provider
var web3js = new Web3(web3.currentProvider);
web3.version.getNetwork((err, netId) => {
switch (netId) {
case "1":
console.log('This is mainnet')
break
case "2":
console.log('This is the deprecated Morden test network.')
break
case "3":
console.log('This is the ropsten test network.')
break
case "4":
console.log('This is the Rinkeby test network.')
break
case "42":
console.log('This is the Kovan test network.')
break
default:
console.log('This is an unknown network.')
}
})
} else {
console.log('No web3? You should consider trying MetaMask!')
}
}
这是我在chrome控制台中获得的输出:
很明显,在某些时候,MetaMask正在基于前两行正确定义web3,但是然后反应会抛出一个错误,说明web3没有为它出现的实例定义if(typeof web3!=='undefined').我尝试过的所有内容都会导致相同的错误或web3无法加载.
1> YD1m..:
您应该在浏览器中使用MetaMask等web3提供程序.这是我用于web3检测的脚本:
window.addEventListener('load', function () {
if (typeof web3 !== 'undefined') {
window.web3 = new Web3(window.web3.currentProvider)
if (window.web3.currentProvider.isMetaMask === true) {
window.web3.eth.getAccounts((error, accounts) => {
if (accounts.length == 0) {
// there is no active accounts in MetaMask
}
else {
// It's ok
}
});
} else {
// Another web3 provider
}
} else {
// No web 3 provider
}
});