【发布时间】:2021-03-24 07:50:27
【问题描述】:
我有一个简单的用户界面,我需要一个元掩码连接按钮 但是当我使用这段代码时,我不断得到 “检测到非以太坊浏览器。你应该考虑试试 MetaMask!”即使我在浏览器中运行了 metamsk 也会出错
这是这里的代码:
window.addEventListener('load', async () => {
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
await ethereum.enable();
var accounts= await web3.eth.getAccounts();
var option={from: accounts[0] };
} catch (error) {
// User denied account access...
}
}
// Legacy dapp browsers...
else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Acccounts always exposed
web3.eth.sendTransaction({/* ... */});
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
const ethereumButton = document.querySelector('.enableEthereumButton');
const showAccount = document.querySelector('.showAccount');
ethereumButton.addEventListener('click', () => {
getAccount();
});
async function getAccount() {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
showAccount.innerHTML = account;
};
这是帐户和连接的 2 个按钮
<button class="enableEthereumButton">Enable Ethereum</button>
<h2>Account: <span class="showAccount"></span></h2>
我需要做些什么来完成这项工作,我遵循了元掩码教程,但它们写得太糟糕了,几乎没用
【问题讨论】:
标签: javascript ethereum web3js metamask