1

I need to redirect to the root page when user tries to refresh the current page in browser. The default behavior is opening the same page. I tried to redirect using onBeforeUnload (this answer) and window.location.replace or Navigator.push but neither worked.

navid
  • 1,022
  • 9
  • 20

1 Answers1

4

What worked for me is checking refresh status in JS (check reload), then redirecting. So I added a check before loading flutter code in index.html:

<script>

function isReload() {
  try {
    return (
      (window.performance.navigation && window.performance.navigation.type === 1) ||
        window.performance.getEntriesByType('navigation').map((nav) => nav.type).includes('reload')
    );
  } catch(err) {
    return false;
  }
}

if (isReload()) {
  console.log("Page accessed by reload, redirecting...");
  window.location.replace('/');
} else {
  window.addEventListener('load', function(ev) {
  // Download main.dart.js
  _flutter.loader.loadEntrypoint({
    serviceWorker: {
      serviceWorkerVersion: serviceWorkerVersion,
    }
  }).then(function(engineInitializer) {
    return engineInitializer.initializeEngine();
  }).then(function(appRunner) {
    return appRunner.runApp();
  });
  });
}

</script>
navid
  • 1,022
  • 9
  • 20