I'm just getting started with Solidity and Truffle, and I'm quite confused regarding this example code:

App = {
  web3Provider: null,
  contracts: {},
  initWeb3: function() {
    // Is there an injected web3 instance?
        if (typeof web3 !== 'undefined') {
            App.web3Provider = web3.currentProvider;
            web3 = new Web3(web3.currentProvider);
        } else {
             // If no injected web3 instance is detected, fallback to the TestRPC.
            App.web3Provider = new web3.providers.HttpProvider('http://localhost:8545');
            web3 = new Web3(App.web3Provider);
    return App.initContract();

In the InitWeb3 function, it checks the type of a variable named web3, but it doesn't seem to be instantiated anywhere. I read that programs like MetaMask can "inject" a web3 instance, but how does this work? How does my program see it?

  • guys. I have some S3 buckets on AmazonWebServices and now some files doesn't work and are infected by MetaMask (I have the extension on my Chrome browser). wtf? How can I fix this? Should I have to uninstall MetaMask? Thanks,
    – Aldc
    Commented Oct 20, 2017 at 9:00
  • If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review Commented Oct 20, 2017 at 16:24
  • Can't you inject web3 with dependency libraries or CDNs? Why yo need a browser plugin? I cannot understand it. Thanks Commented Nov 7, 2017 at 11:07
  • @AlexAcc the point of metamask is not to just inject Web3. You can import the Web3 javascript library yourself and use it normally. Metamask however uses Web3 and also it's own Web3Provider in order to couple web3 with metamask functionality (such as signing transactions). So, I suppose it makes sense for it to instantiate the web3 instance for you.
    – Alexmedkex
    Commented May 8, 2018 at 10:45

2 Answers 2


The MetaMask WebExtension uses a contentscript to write a script tag into the DOM of every web page you visit. This script tag exposes the web3 API, and allows your application to query it and propose transactions to the user.

If you don't see web3 available, it's possible you're seeing a known bug in Chromium, and should wait a little longer. Usually the document ready event is late enough to see the injected web3 take effect.


The Chrome plugin Metamask inject a global variable web3 in your browser. You can see it in your console browser, you have this message MetaMask - injected web3 and you can see the web3 object by taping web3 in your console. MetaMask is a proxy between the server side and your browser interface. Your program can see this variable only when it's loading with your browser.

Your Answer

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

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