3

I'm a bit of a noob in javascript and I need some help.

My objective is to create a client-side javascript program that uses Metamask as web3 provider and display the output of some web3 functions on the screen.

I found a snippet of code that should fetch the web3 provider from MetaMask here or write a warning message to the dev console.

I unsuccessfully tried to get it to run buy opening a file in my browser that has the following lines of code:

<html>
  <body>
    <script type="text/javascript">
      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);
      console.log('Got a web3 provider');
      } else {
      console.log('No web3')
      }

      })
      </script>
  </body>
</html>

This writes to the console 'No web3'. I am definitely logged in to MetaMask, which is showing my balance on the main net.

Question: Why does this not work and how to I get it to work?

  • Have you tested using window as the scope for web3? typeof window.web3 !== 'undefined' – ReyHaynes May 15 '18 at 14:06
4

What metamask do is inject javascript into the document when you access it. The browser will execute this javascript, and is that execution that will define de variable web3.

But when you are accessing a document by accessing the file (your url will start with file://) then metamask will not inject the javascript, so the variable web3 will be undefined.

Try accessing your file through a web server of some sort and it will work.

  • Yeap, it is not comfortable for developing local scripts and pages. – Stepan Poperechnyi Jan 22 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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