'Non-Ethereum browser detected. You should consider trying MetaMask
Im having a simple UI where i need a metamask connect button but when i use this code i keep getting the "Non-Ethereum browser detected. You should consider trying MetaMask!" error even though i have metamsk up an running in my browser
This is the code here:
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;
};
and this are the 2 buttons for account and to connect
<button class="enableEthereumButton">Enable Ethereum</button>
<h2>Account: <span class="showAccount"></span></h2>
What do I need to do to make this work, i followed the metamask tutorial but they are written so bad, they are almost useless
Solution 1:[1]
You dont need to use window for metamask access. You can try replacing your if with somthing like this.
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...
}
}
The getAccount() function isn't neccesary as you should be able to pull everything from the web3.eth.* anyway.
Solution 2:[2]
Try to run this code inside a server such as Apache, nginx.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | J G |
Solution 2 | Codemaker |