I use code like this to get my Ethereum balance with web3
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="./web3.min.js"></script>
<script type="text/javascript">
window.addEventListener('load', function () {
if (typeof web3 !== 'undefined') {
console.log('Web3 Detected! ' + web3.currentProvider.constructor.name)
window.web3 = new Web3(web3.currentProvider);
} else {
console.log('No Web3 Detected... using HTTP Provider')
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
})
function getBalance() {
var address, wei, balance
address = document.getElementById("address").value
try {
web3.eth.getBalance(address, function (error, wei) {
if (!error) {
var balance = web3.fromWei(wei, 'ether');
document.getElementById("output").innerHTML = balance + " ETH";
}
});
} catch (err) {
document.getElementById("output").innerHTML = err;
}
}
</script>
</head>
<body>
<h1>ETH Balance Fetcher</h1>
<p>Enter your Ethereum Address:</p>
<input type="text" size="50" id="address" />
<button type="button" onClick="getBalance();">Get Balance</button>
<br />
<br />
<div id="output"></div>
</body>
</html>
But it does not work for tokens.
For example i create ERC20 and contract adress is
0xa318948fd693281fa6a95a409b3efb79e228edec
(I add it in metamask and it shows my token balance)
How can I read it with web3? tnx for helping