How to Get web3.js Working – Comprehensive Guide

metamaskrinkebyweb3js

I am a new learner. I am confusing on how to get the web3.js work on a shared hosting. The user who uses the function must have Metamask installed.

As I am using shared hosting, I can't install the node or geth on the shared hosting.

I downloaded the web3.js from https://github.com/ethereum/web3.js/ and uploaded the files to the shared hosting then linked to the HTML file.

<script src="assert/dist/web3.js></script>

I follow the guide on this post
Is it possible to use web3.js API methods to interact with a contract deployed on Rinkeby?

and add the code to the tag

I am using a domain with https://

I am using Google Chrome browser.

I installed Metamask and logged in, connected to the Rinkeby Test Network.

enter image description here

I upload the following HTML file to the shared hosting server and run it but got the error

Below is the full HTML code I used for testing.

<!doctype>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Project</title>
<script src="assets/dist/web3.js"></script>
<script>
    var Web3 = require('web3');
    var web3 = window.web3;

    if(typeof web3 !== 'undefined') {
        console.log("Using web3 detected from external source like Metamask");
        web3 = new Web3(web3.currentProvider);
    } else {
        console.log("Using localhost");
        web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    }

    var account = web3.eth.accounts[0];
    console.log(account);
</script>
</head>
<body><p>Hello Project</p></body>
</html>

enter image description here

The HTML web3.js cannot detect the Rinkeby Test Network as the provider.

What have I miss? Advises are much appreciated. Thanks

Best Answer

Main problem here is you specify as node localhost:8545 which should correspond to a local node on your machine.

If your user has metamask you don't need to instanciate a Web3 object yourself, Metamask already does it by injecting in your browser the web3 instance in window.web3. Metamask will then catch the transactions when using this instance to make calls and will rely the transaction - if accepted by user - to the currently connected network.