I've been trying to get rid of this error, but no matter how much I try, I just can't figure this out. I've finished the tutorials of cryptoZombies, and all I know about web3 I got from there.
I created the simplest app possible to show the error I'm getting. This is my contract, deployed on Ropsten:
pragma solidity ^0.4.24;
contract SimpleRegister {
string name;
function setName(string _name) external {
name = _name;
}
function getName() external view returns (string) {
return (name);
}
}
My frontend is the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./web3.min.js"></script>
<script language="javascript" type="text/javascript" src="abi.js"></script>
</head>
<body>
<div class="container">
<h1>Simple Register</h1>
<h2 id="display"></h2>
<button type="submit" onclick="getName();return false;">Get Name</button>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
window.addEventListener('load', function() {
if (typeof web3 !== 'undefined') {
web3js = new Web3(web3.currentProvider);
}
else {
this.alert("Install Metamask.");
}
startApp();
});
function startApp() {
var contractAddress = "0x715e99e73deefdb06f9d1e55172cbc52307eda5b";
simpleRegister = new web3js.eth.Contract(contractABI, contractAddress);
}
function _getName() {
return simpleRegister.methods.getName().call();
}
function getName() {
_getName().then(function(result) {
$("#display").html(result[0]);
console.log(result);
});
}
</script>
</body>
</html>
Does anyone has an idea about what's going on and how to fix that? Thank you.
Best Answer
You cannot just open the html file and have MetaMask inject it's web3 instance in.
From the MetaMask documentation:
The easiest way round this is to use Python's SimpleHTTPServer from the project root directory:
You can then visit http://localhost:8000 in the web browser with MetaMask extension installed.