【问题标题】:Non-Ethereum browser detected. You should consider trying MetaMask检测到非以太坊浏览器。您应该考虑尝试 MetaMask
【发布时间】: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


    【解决方案1】:

    您不需要使用窗口进行元掩码访问。你可以尝试用这样的东西替换你的 if。

    if (window.ethereum) {
        const web3 = new Web3(ethereum);
        try {
            await ethereum.enable();
            var accounts = await web3.eth.getAccounts();
            console.log(accounts)
    
        } catch (error) {
            // User denied account access...
        }
    }
    

    getAccount() 函数不是必需的,因为您应该能够从 web3.eth.* 中提取所有内容。

    【讨论】:

    • 如果没有必要,为什么要把它留在里面?
    • 我在代码 sn-p 的底部引用了异步函数。 getAccount() 不是 getAccounts()
    猜你喜欢
    • 2020-03-31
    • 2022-09-17
    • 1970-01-01
    • 2015-11-13
    • 2019-03-29
    • 2020-01-27
    • 1970-01-01
    • 2012-05-02
    • 2012-08-24
    相关资源
    最近更新 更多