I'm building an Angular app which connects to various blockchain accounts through metamask. One of my services connects to MetaMask by obtaining a provider and signer using

this.myProvider = new ethers.providers.Web3Provider(window.ethereum);
this.mySigner = this.myProvider.getSigner();

I would like my service to be aware when the user switches accounts or chains, or signs out of metamask and I am trying to find a way to be informed of those events when they happen.

I see that the object returned to myProvider is a Web3Provider, which contains an addListener method which takes 2 parameters, an EventType and a Listener but I can't find any documentation on how to access valid Event Types or how to set up a listener I assume that these events might provide what I am looking for. Can somebody point me to an example of how to use these events and listeners?

2 Answers 2


Those events are part of EIP-1193 definition of the provider API, they are not part of ethers.js or web3.js if I understand correctly. A nice documentation is also present here.

So to access them, you need to call directly on window.ethereum that is injected by Metamask.

window.ethereum.on("accountsChanged", (accounts) => {
/* do what you want here */

Similarly to watch for chain change :

window.ethereum.on("chainChanged", (chainId) => {
/* do what you want here */
/* full refresh is recommended */

I'm wondering the same ... I find out as @hroussille, but now, how can i properly use that in an Angular app... That's the question !

EDIT --- I found something !

In the constructor of a service i write something like that :

constructor() {
 (window as any).ethereum.on('accountsChanged',(accounts) =>{

And it's working :)

  • If you want to set the listeners in a component, suggest you put the code as suggested by @hroussille in ngOnit method of your component. I'm not positive if this is true, but you may also need to add a teardown method in ngOnDestroy to tear down these listeners to avoid memory leaks.
    – GGizmos
    Dec 4, 2021 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.