当我尝试通过web3js和MetaMask调用以太坊智能合约时,遇到了获取window.web3的问题。消息显示该值未定义。
<script src="jquery.min.js"></script>
<script src="web3.min.js"></script>
<script type="text/javascript">
window.addEventListener('load',
function() {
$("#loader").hide();
console.log('!');
web3 = window.web3;
console.log(web3);
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use Mist/MetaMask's provider
web3 = new Web3(web3.currentProvider);
window.web3 = new Web3(web3.currentProvider);
console.log(web3.currentProvider);
if (web3.currentProvider.isMetaMask === true) {
startApp();
} else {
$('#results').html('No web3? Please use google chrome and metamask plugin to enter this Dapp!');
}
}
});
...
控制台:
!
未定义
答案 0 :(得分:2)
window.web3。因此,如果您在空白(about:blank)页面或本地文件中运行此代码而未运行本地服务器(URL以file:///开头),则窗口范围内将不会存在web3对象