It seems that on my computer/web browser Google Chrome is slow to inject meta-mask. Therefore I have to write something like this for my App to actually get the web3 instance instead of failing:

    if (typeof web3 !== 'undefined'){
        console.log('getting web3');
        App.web3Provider = web3.currentProvider;
    else {
        console.log('No Web3 instance given!');
        // flash modal saying "please download Metamask"
    web3 = new Web3(App.web3Provider);

    return App.initContract(web3);

}, 500);

However, this doesn't play nice with Truffle-Contract js library, which needs the web3 instance straight away. Does anyone have a workaround or a fix for this? Thanks.

1 Answer 1


The truffle-contract library doesn't need the web3 instance right away. It only needs it to be there when you start trying to use it.

var contract = require("truffle-contract");
var my_contract_json = require('../../../truffle/build/contracts/MyContract.json');
var MyContract;

var my_contract_deployed;

window.onload = function() {
    if (typeof web3 !== 'undefined') { 
        window.web3 = new Web3(web3.currentProvider);

        MyContract = contract(my_contract_json);
        MyContract.deployed().then(function(instance) {
            my_contract_deployed = instance;
            // doWhateverUIStuff();

See a working example here: https://github.com/realitykeys/realitycheck/blob/8674f7b07cef2c4c96762c30befd549138bdb8e4/assets/js/scripts/main.js#L3398

  • Thank you for the help! I think I was using the truffle-contract library before the web3 instance was received, as you said.
    – Alex
    Oct 14, 2017 at 21:59

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.