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 goerli),
  • changing the active account
<!DOCTYPE html>
<html>
    <head>
        <script>
            window.addEventListener("load", (event)=>{
                if(window.ethereum){


                    // React on changing the network (e.g mainnet => goerli)
                    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>
Categories: