I am trying to connect to MetaMask and I have read their docs about the breaking changes and everything. From what I understand, they are not injecting web3 into window.web3 but instead are using window.ethereum. However, I am using this but when I try to run web3.eth.getAccounts
my code returns an error saying that eth
is not defined, and furthermore that "metamask no longer injects web3". But I thought that I changed this correctly to use window.ethereum?
Here is my code, first I call this function and then set window.web3
to the web3 provider.
async loadWeb3() {
window.addEventListener('load', async () => {
// Modern dapp browsers
if (window.ethereum) {
window.web3 = new Web3(window.ethereum);
await window.ethereum.enable();
// legacy dapp browsers
} else if (window.web3) {
window.web3 = new Web3(window.web3.currentProvider);
} else {
window.alert('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
});
}
After that, I use the provider object and call eth.getAccounts():
async loadBlockchainData() {
const web3 = window.web3;
const accounts = await web3.eth.getAccounts();
}
But I get an error saying that "cannot read property getAccounts of undefined".