Page not reloading when network changes

Hey, I used code from tutorial of network tracking, but when network changes in metamask it doesn’t reload page.

var web3;

checkWeb3();

function displayMessage(messageType, message) {
  messages = {
    "00": `<div class= "alert alert-success"> ${message} </div>`,
    "01": `<div class= "alert alert-danger"> ${message} </div>`,
  };
  document.getElementById("resultSpace").innerHTML = messages[messageType];
}

async function checkWeb3() {
  const ethereum = window.ethereum;
  if (!ethereum || !ethereum.on) {
    displayMessage("01", "This App Requires MetaMask, Please Install MetaMask");
  } else {
    //displayMessage("00", "Metamask is Installed");
    setWeb3Environment();
  }
}

function setWeb3Environment() {
  web3 = new Web3(window.ethereum);
  getNetwork();
  monitorNetwork();
}

async function getNetwork() {
  var chainID = await web3.eth.net.getId();
  console.log(chainID);
  if (chainID == 137) {
    displayMessage("00", "Correct Network");
  } else {
    displayMessage("00", "Wrong Network, please change it to Polygon Mainnet");
  }
}

function monitorNetwork() {
  Moralis.onChainChanged(function () {
    window.location.reload();
  });
}

you could add logging to see if that function it is called

function is called, but it seems like this part doesn’t work image

If you add a console.log in that callback function before reload, it is called?

Also, you have latest version of the sdk?

Yes nothing is called. What do you mean with sdk?

I mean what version you get if you run this: console.log(Moralis.CoreManager.get("VERSION"))

I’ve run it and it is js1.3.2.

ok, that means that you have latest sdk version

What could be problem?

seems something similar: Moralis JS SDK v1.0 (migration to Ethers.js)

I changed code:

function monitorNetwork() {
  ethereum.on("chainChanged", (chain) => {
    window.location.reload();
  });
}

This works

1 Like