I am including web3.js
0.19.0
and getting the following error from the browser console: Uncaught ReferenceError: web3 is not defined at file.html:270
when using it with the following code:
<script src="https://cdn.jsdelivr.net/npm/web3@0.19.0/dist/web3.js"></script>
<script>
window.addEventListener('load', function () {
if (typeof web3 !== 'undefined') {
console.log('Web3 Detected! ' + web3.currentProvider.constructor.name)
web3 = new Web3(web3.currentProvider);
} else {
console.log('No Web3 Detected... using HTTP Provider')
web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/key"));
if(!web3.isConnected())
console.log("not connected");
else
console.log("connected");
}
});
web3.eth.defaultAccount = "0x..."; // <-- here starts the error "web3 undefined!!"
var myContract = web3.eth.contract(...abi...);
var myInstance = myContract.at('0x...');
</script>
On the other hand the browser gives me a positive message and tells me:
No Web3 Detected... using HTTP Provider (because I don't use Metamask)
connected
So how can web3 not being defined, if I get a connection with it?
Best Answer
The web3 instance within your
if
statement comes from thewindow
object. This occurs when MetaMask/Mist/Cipher injects it into the browser.If you enter the
else
statement, this means that no web3 instance was found on thewindow
object. So, you manually create one from another provider (Infura, in your case). Either way, web3 will be defined (in one way or another) after theif...else
statements.Once you have a defined instance of web3, you need to do something with it from within the
addEventListener()
function since it is asynchronous. Depending on how you are structuring you application, you could call astartApp()
function (or another type of callback) which will have access to your defined web3 instance.