DEV Community

Karthick S
Karthick S

Posted on

How to Switch to Particular Network using Window.Ethereum

In Web3, Almost Every Dapps were connected to a Particular Network. For Example, Beginners and Learning based projects are mostly connected to a Test Network.

When a Transaction triggered by the user, the Metamask will be connected and Perform the Transaction.In this, the user needs to manually Switch to a Particular Network to perform the Transaction.

Suppose, if the user is new to web3, he doesn't know! What network he need to switch.

So for that Coming up with the solution. Switch Network/chain in Metamask.

Here is a JavaScript Program to Switch from one Network or chain to other:

const SwitchNetwork = async (_chainId) => {
    let chainId = _chainId;
    await window.ethereum
        method: "wallet_switchEthereumChain",
        params: [{ chainId: chainId }],
      .then(() => console.log("Successfully! Connected to the requested Network"))
      .catch((err) => {
        if (err.message.startsWith("Unrecognized chain ID")) {
Enter fullscreen mode Exit fullscreen mode

From the above in catch() block, you can find addNetwork(). This will help the user to add Automatically connected to the Network,Which doesn't exist in his Metamask.

To know addNetwork(), Follow this!

                        Happy Coding!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)