我从github上获得了这段代码,它允许您使用web3.js连接到MetaMask并支付费用。然后我把它修改成
当用户未登录时,通过检查元素的内容是否为空,连接按钮将显示连接按钮,如果该元素不为空,则连接按钮hidden.
我希望连接到的钱包在MetaMask连接后立即显示并隐藏连接按钮,但在手动重新加载页面之前它不会这样做
下面是我的代码
<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> 您的帮助将不胜感激!
谢谢你的帮助。
发布于 2022-03-12 00:15:39
您应该使用类似于此window.onload = async function () {的onload函数,当它工作时,您需要验证窗口是否有ethereum,如果一切正常,然后使用new Web3.providers.HttpProvider连接到提供程序
window.onload = async function () {
const detectMM = () => typeof window.ethereum !== "undefined";
if (detectMM) {
document.getElementById("enableMM").getAttribute("disabled", false);
try {
const provider = new Web3.providers.HttpProvider(
"HTTP://127.0.0.1:7545"
);
web3 = new Web3(window.ethereum);
web3Host = new Web3(provider);
await connect();
await web3.eth.net
.isListening()
.then(
() =>
(document.getElementById(
"network"
).innerHTML = `available network`)
)
.catch(
(e) =>
(document.getElementById(
"network"
).innerHTML = `Something went wrong: ${e}`)
);
} catch (error) {
alert(error);
}
} else {
document.getElementById("enableMM").getAttribute("disabled", true);
}https://stackoverflow.com/questions/70749136
复制相似问题