I am unable to contact the local testrpc server that I set up when I am executing the javascript file through a webpage. Everything works fine when the js file is executed from the node console

My html code:

        <script type="text/javascript" src="./malware.js"></script>

malware.js file

//create web3 object
const Web3 = require('web3');
const fs = require('fs');

var web3 = new Web3(new 
var code = fs.readFileSync('malware.sol').toString();

//deploy a smart contract instance from a node using code information generated during compilation
var malwareContract = web3.eth.contract(contract.info.abiDefinition);
var deployedContract = malwareContract.new({data: contract.code, from: web3.eth.accounts[0], gas: 4700000});

//save the smart contract instance to access it later
var contractInstance = malwareContract.at(/*here the value obtained from contractInstance.address in the node console is used*/);

//here I am using an alert to check contractInstance.address

No part of the javascript code is running when it is accessed through the webpage.When I uncomment the first alert, nothing happens. However when I am running the same code in node console everything is printing as expected.

On further research, I found that require functions can't be directly called from a webpage. What is the alternative for using web3 libraries


you need to load the web3js in you webpage. the require function works only for nodejs not conventional javascript in a browser.

so first download form github repo.

add to your webpage the following ligne to load the web3js

  <script type="text/javascript" src="web3.min.js"></script>

and in your malware file (what a name) add in the beginning the web3 object definition :

if(typeof window.web3 !== "undefined" && typeof window.web3.currentProvider !== "undefined") {
            var web3 = new Web3(window.web3.currentProvider);
          } else {
            var web3 = new Web3();
| improve this answer | |

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.