Skip to content

Instantly share code, notes, and snippets.

@kennethhutw
Created October 21, 2020 18:12
Show Gist options
  • Save kennethhutw/a30cd65a8af7709c055d6c01aa28a208 to your computer and use it in GitHub Desktop.
Save kennethhutw/a30cd65a8af7709c055d6c01aa28a208 to your computer and use it in GitHub Desktop.
Detecting Metamask account or network change in Javascript using Web3 1.2.4
window.addEventListener("load", function() {
if (window.ethereum) {
// use MetaMask's provider
App.web3 = new Web3(window.ethereum);
window.ethereum.enable(); // get permission to access accounts
// detect Metamask account change
window.ethereum.on('accountsChanged', function (accounts) {
console.log('accountsChanges',accounts);
});
// detect Network account change
window.ethereum.on('networkChanged', function(networkId){
console.log('networkChanged',networkId);
});
} else {
console.warn(
"No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live",
);
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
App.web3 = new Web3(
new Web3.providers.HttpProvider("http://127.0.0.1:7545"),
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment