2

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:

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

malware.js file

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

var web3 = new Web3(new 
Web3.providers.HttpProvider("http://localhost:8545"));
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
alert(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

3

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();
          }

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.