How to Listen for Network Changes on OP_WALLET
Monitoring network changes in OP_WALLET is essential for applications that need to adapt to different blockchain environments. This guide explains how to listen for network change events using OP_WALLET's on()
method.
Method
on(event: "chainChanged" | "networkChanged", listener: (network: UnisatNetwork) => void): void;
-
Parameters:
event: "chainChanged" | "networkChanged"
: The event to listen for.listener: (network: UnisatNetwork) => void
: The callback function to execute when the event is triggered.
Example Code
opnet.on("chainChanged", (chainId) => {
console.log("Network changed to:", chainId);
});
Best Practices
- Ensure
window.opnet
is available before registering event listeners. - Use the
chainId
to adapt your application to the correct network settings. - Use the
removeListener
method to avoid memory leaks when the listener is no longer needed:opnet.removeListener("chainChanged", listener);
What’s Next?
- Learn how to Request Accounts from OP_WALLET
- Explore Fetching Public Key Information