How to get the network ID by a method other than "window.ethereum.on('chainChanged', async (chainId) =>" when changing the network after connecting MetaMask to DApps

If I connect MetaMask to a DApps, even if I change the network, will “await;” only return the network ID selected when I connected to the DApps?

If I have not connected my MetaMask account to the DApps, when I change the network, “await;” returns the changed network ID, but if I connect MetaMask to the DApps, “await;” returns only the network ID selected when connecting to the DApps.

Is there a way to get the changed network ID even after connecting MetaMask to the DApps, other than “window.ethereum.on(‘chainChanged’, async (chainId) =>”?

useEffect(() => {           
    if (window.ethereum) {
        window.ethereum.on('chainChanged', async (chainId) => {
            console.log("chainId", chainId);

}, []);

const checkNetworkAndLoadData = async () => {
    if (window.ethereum) {
        try {
            const web3 = new Web3(window.ethereum);
            const currentNetworkId = await;
            console.log("currentNetworkId", currentNetworkId);                
        } catch (error) {
            console.error("An error occurred:", error);
1 Like

Hi I found javascript - How to change network in metamask using react js - Stack Overflow did you try using MetaMask API method MetaMask developer documentation

1 Like

Thank you for your reply. :smiling_face_with_three_hearts:

Even if I changed the network after connecting MetaMask to DApps, “window.ethereum.networkVersion” returned the changed network ID as expected.

This is a big discovery, but “window.ethereum.networkVersion” displays the following warning. It does not seem to be a recommended method.

“VM6221:1 MetaMask: ‘ethereum.networkVersion’ is deprecated and may be removed in the future. Please use the ‘net_version’ RPC method instead.”

With the recommended “window.ethereum.request({ method: ‘net_version’ })” and “await ethereum.request({ method: ‘eth_chainId’ });”, if I changed the network after connecting MetaMask to DApps, it only returned the network ID at the time of connection, not the changed network ID.

It seems that “window.ethereum.networkVersion” may be removed, so I would like to know if there is an alternative way to obtain the network ID.


1 Like

Thanks for more details, could you please check this discussion and maybe add a comment there: Deprecating Legacy Provider Properties, `networkChanged` event, and `send()` `net_version` support · MetaMask/metamask-improvement-proposals · Discussion #23 · GitHub

1 Like

I added a comment. Thanks.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.