Reacting on Provider Events

Published by Mario Oettler on

Sometimes it is necessary to react to a change of the active account or on an interruption of network connection.

The client (e. g. website) can react to events from the provider with ethereum.on.

ethereum.on('eventName', function(parameters) => {
  // react on the event
});

One defines the event name and provides a handler to execute code if the event occurs. In this function, parameters collect the values send along with the event.

Here are two examples. We want to react on:

  • changing the network (e.g., mainnet to sepolia),
  • changing the active account
<!DOCTYPE html>
<html>
    <head>
        <script>
            window.addEventListener("load", (event)=>{
                if(window.ethereum){
                    console.log("Ethereum ist da");

                    // React on changing the network (e.g mainnet => sepolia)
                    ethereum.on('chainChanged', function(res){
                        console.log(res);
                        document.getElementById("network").innerHTML = "Network: " + res;
                    })

                    ethereum.on("accountsChanged", function(res){
                        console.log(res);
                        document.getElementById("account").innerHTML = "Account: " + res;
                    })

                   
                }else{
                    return false
                }
            })
            
        </script>
    </head>
    <body>
        <h1>Using the Provider API</h1>
        <div id = "network"></div>
        <div id = "account"></div>
    </body>
</html>

You might realize that there is no reaction on the accountChanged event when switching to another account in MetaMask. The event is only fired if the selected account is connected to the website.

An unconnected account is marked with a grey dot next to it in the accounts list. At the bottom of the plugin window, there is also a message that lets you connect the account.

The selected account is the first account in the array:

[account X, account Z, account B]

Account X is the currently selected account.

Categories: