Web3js MetaMask – Unable to Detect MetaMask in Browser

metamaskweb3-providersweb3js

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?

Best Answer

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.