5

I want to create a simple page to interact with my deployed contract. I don't want to use Node.js. I want to use html + web3.js browser version. I got a link: https://github.com/ethereum/web3.js/tree/develop/dist

But the above link contains web3.js files that contains "require" keyword which cannot run in browser. I want browser version of web3.js.

1
  • The files you find there are the correct ones to use in the browser. If you're encountering some sort of error when you try, please share your code and the error you're seeing.
    – user19510
    Aug 3, 2018 at 21:16

2 Answers 2

5

For web3.js 1.0, I got it working like this:

In head:

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/web3.min.js"></script>

Then get a reference to it:

<script>
var web3js = new Web3(new Web3.providers.HttpProvider('https://testnet-rpc.gochain.io'));
</script>

And use it like this:

var contract = new web3js.eth.Contract(abi, address);

Hope that helps!

1
  • Why instantiating Web3 within Web3? (new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545')))
    – errata
    Mar 30 at 15:03
1

Use script tag to include web3.js in any html:

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>

Following code snippet will check for any injected web3.js instance(Metamask etc). if not then will fallback to local geth node or infura endpoints.

function initweb3 () {   
    if(type of web3 !== 'undefined') {
        // Use injected web3
        web3js = new Web3(web3.currentProvider);
    } else {
        /* Fallback to local node or remote node               
        by default local HTTP-RPC server exposes port 8545.
        you can use Infura Node Urls also
        'https://ropsten.infura.io/<API KEy>'*/    
        web3js = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545'));
    }
}
                 
// You should initialize web3 instance after window load event has fired to avoid any race condition.               
window.addEventListener('load',initweb3);
5
  • Throws "cb" is not defined error. I am not using node.js
    – Vivek Sadh
    Aug 3, 2018 at 7:45
  • cb here is notation for callback function, after onLoad event, which function you want to call, put that function in place of "cb"
    – kherwa
    Aug 3, 2018 at 7:49
  • Made modifications in code.
    – kherwa
    Aug 3, 2018 at 8:02
  • HOw do I use es6 module import?
    – chovy
    Dec 10, 2021 at 6:38
  • Why instantiating Web3 within Web3? (new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545')))
    – errata
    Mar 30 at 15:03

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.