Uncaught ReferenceError: web3 is not defined at window.onload

6.2k views Asked by At

I'm trying to get my first dapp working; I know I'm close, but keep running into a problem with web3.

I am working on Windows 10, running a testrpc node via PowerShell. I used truffle to set up my folders & sample files, then compile and migrate.

I don't think I changed anything from the app.js file built by truffle... here is that code:

var accounts;
var account;

function setStatus(message) {
  var status = document.getElementById("status");
  status.innerHTML = message;
};

function refreshBalance() {
  var meta = MetaCoin.deployed();

  meta.getBalance.call(account, {from: account}).then(function(value) {
    var balance_element = document.getElementById("balance");
    balance_element.innerHTML = value.valueOf();
  }).catch(function(e) {
    console.log(e);
    setStatus("Error getting balance; see log.");
  });
};

function calcPremium() {
    var premium = parseInt(document.getElementById("benefit").value)/10000;
    document.getElementById("monthlyPremium").innerHTML = "    Monthly Premium: $"+premium.toFixed(2);

};

function sendCoin() {
  var meta = MetaCoin.deployed();

  var amount = parseInt(document.getElementById("monthlyPremium").value);
  var receiver = document.getElementById("receiver").value;

  setStatus("Initiating transaction... (please wait)");

  meta.sendCoin(receiver, amount, {from: account}).then(function() {
    setStatus("Transaction complete!");
    refreshBalance();
  }).catch(function(e) {
    console.log(e);
    setStatus("Error sending coin; see log.");
  });
};

window.onload = function() {
  web3.eth.getAccounts(function(err, accs) {
    if (err != null) {
      alert("There was an error fetching your accounts.");
      return;
    }

    if (accs.length == 0) {
      alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
      return;
    }

    accounts = accs;
    account = accounts[0];

    refreshBalance();
  });
}

I'm able to open the html file in a Chrome browser, with the MetaMask plugin enabled. However, it seems I'm unable to interact with the contracts in any way, due to the web3 error issue. The exact message is this post's subject line.

Thanks in advance for any help or guidance!

1

There are 1 answers

2
Ranadip Dutta On BEST ANSWER

Could you please try it and see . I think the onload is giving the issue.

    $(window).load function() {
  web3.eth.getAccounts(function(err,accs) {
    if (err != null) {
      alert("There was an error fetching your accounts.");
      return;
    }

    if (accs.length == 0) {
      alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
      return;
    }

    accounts = accs;
    account = accounts[0];

    refreshBalance();
  });
}