I got this code off github which allows you to connect to MetaMask using web3.js and also to make payment. I then modified it to
- Display a Connect Button when user is not logged in by checking if the content of an element is empty and if it is not empty, the connect button is hidden.
- Retrieve the connected wallet address which is in the element that hides the button.
I want the connected wallet to show up and hide the Connect button as soon as MetaMask is connected but it does not do that until i manually reload the page
Below is my code
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://unpkg.com/@metamask/legacy-web3@latest/dist/metamask.web3.min.js"></script>
</head>
<body>
<div>
<div id="selected-account"></div>
<button class="pay-button">Pay</button>
<div id="status"></div>
<div id="accTabs"></div>
</div>
<script type="text/javascript">
async function initWeb3() {
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
await ethereum.enable();
window.location.reload();
} catch (err) {
$("#status").html("User denied account access", err);
}
} else if (window.web3) {
return (window.web3 = new Web3(web3.currentProvider));
} else {
return $("#status").html("No Metamask (or other Web3 Provider) installed");
}
}
selectedAccount = ethereum.selectedAddress;
document.querySelector("#selected-account").textContent = selectedAccount;
$(".pay-button").click(async () => {
await initWeb3();
// paymentAddress is where funds will be send to
const paymentAddress = "0x192c96bfee59158441f26101b2db1af3b07feb40";
const amountEth = "1";
web3.eth.sendTransaction(
{
to: paymentAddress,
value: web3.toWei(amountEth, 'ether')
},
(err, transactionId) => {
if (err) {
console.log("Payment failed", err);
$("#status").html("Payment failed");
} else {
console.log("Payment successful", transactionId);
$("#status").html("Payment successful");
}
}
);
});
</script>
<script>
if ($('#selected-account').text() == '') {
document.getElementById("accTabs").innerHTML = '<button onclick="initWeb3()">Connect Ethereum</button>';
} else {
}
</script>
</body>
</html>
Your help will be appreciated!
Thanks for your assistance.