Uncaught ReferenceError: web3 is not defined in Web3.js
Dung Do Tien
Jul 09 2022
427
Hi guys. I am a newbie in blockchain and I want to use Web3 .js to help me connect to the Metamask wallet from the desktop. I try to create an instance of web3 like this:
var web3_init;
if (typeof parent.ethereum !== 'undefined') {
web3_init = new Web3(parent.ethereum);
} else if (typeof ethereum !== 'undefined') {
web3_init = new Web3(ethereum);
} else {
web3_init = new Web3(web3.givenProvider);
}
In case, the browser does not install the Metamask extension else
case will be called. and it throws an exception Uncaught ReferenceError: web3 is not defined. You can see the full exception here:
VM781:1 Uncaught ReferenceError: web3 is not defined
at eval (eval at connectWeb3 (index.html?m=normal&v=21.4.1.1&a=0x2170ed0880ac9a755fd29b2688956bd959f933f8&n=bsc&t=false:525:21), <anonymous>:1:1)
at connectWeb3 (index.html?m=normal&v=21.4.1.1&a=0x2170ed0880ac9a755fd29b2688956bd959f933f8&n=bsc&t=false:635:21)
at HTMLButtonElement.onclick (VM761 0x2170ed0880ac9a755fd29b2688956bd959f933f8:690:276)
eval @ VM781:1
connectWeb3 @ index.html?m=normal&v=21.4.1.1&a=0x2170ed0880ac9a755fd29b2688956bd959f933f8&n=bsc&t=false:635
onclick @ VM761 0x2170ed0880ac9a755fd29b2688956bd959f933f8:690
Can anyone help me?
I really appreciate any help you can provide.
Have 1 answer(s) found.
-
P0
P Jul 09 2022
When using
Web3.js
it will be set with the current native provider by that browser.It will return the given provider by the browser
If not, it will return NULL. So I think you can handle it something like this:
if (typeof web3 == 'undefined') { alert('MetaMask is not available. Please install it first.') } else { web3ojb = new Web3(web3.givenProvider); }
I usually check it and alert to end-user like above. Hope it can help you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.