Reputation: 486
When I try to invoke an Ethereum smart contract via web3js and MetaMask, I encounter the problem with getting window.web3. The message says that the value is undefined.
<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!');
}
}
});
...
Console:
!
undefined
Upvotes: 3
Views: 4097
Reputation: 892
window.web3 is injected by MetaMask only when viewing a page with http or https protocol. So effectively there wont be a web3 object in window scope if you are running this code in a blank (about:blank) page or in a local file without running a local server (URL starting with file:///)
Upvotes: 11