4

I've been working with this project and I downloaded all dependencies and Web3 already but when I test my code it shows me this:

Uncaught ReferenceError: Web3 is not defined

in line 120.

This is my code:

<script>
if(typeof web3 !== 'undefined'){
    web3 = new Web3(web3.currentProvider); -this is where it errors
}else {
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); 
}

web3.eth.defaultAccount = web3.eth.accounts[0];

var SuffrageContract = web3.eth.contract('example');
var Suffrage = SuffrageContract.at('example');
console.log(Suffrage);

I have already tried several methods like declaring

web3 = required('web3');

but it is still not working.

5
  • Can you please include more? Sanity check: did you include the web3.js file? Jul 6, 2018 at 8:02
  • Yes I included web3.js
    – JeffNUCode
    Jul 6, 2018 at 8:28
  • 2
    try including <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script> Jul 6, 2018 at 8:35
  • 1
    Thank you Mr. Achala Dissanayake! My project is running now!
    – JeffNUCode
    Jul 6, 2018 at 8:39
  • 1
    Yes. :) You rock dude.
    – JeffNUCode
    Jul 6, 2018 at 8:41

2 Answers 2

4

I hope you are using web3 as browser module.

As in their documentation, you can add the CDN link using <script> tags as below,

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
2
  • 1
    Cant up this because I have less than 1 rep. But anyway thanks! Its working now because of you. :)
    – JeffNUCode
    Jul 6, 2018 at 8:42
  • @JeffNUCode Hope you can up now :D Jun 17, 2021 at 3:06
1

Are you wrapping this code with a window.addEventListener('load',...) handler?

Read here: Web3 - Ethereum Browser Environment Check

Note that the environmental web3 check is wrapped in a window.addEventListener('load', ...) handler. This approach avoids race conditions with web3 injection timing.

window.addEventListener('load', function() {

  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  if (typeof web3 !== 'undefined') {
    // Use Mist/MetaMask's provider
    web3js = new Web3(web3.currentProvider);
  } else {
    console.log('No web3? You should consider trying MetaMask!')
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    web3js = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  }

  // Now you can start your app & access web3 freely:
  startApp()

})
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.