Last Updated: September 09, 2019
·
1.08K
· magalhini

Prevent page from going anywhere

While working on an old fashioned "traditional" website (not a web app), I often had to inspect/debug pages that were automatically redirecting themselves somewhere else without having a way to prevent them from doing so in the code.

So I came up with something in the browser that will prevent them from going away.

(function() {
  var blocked = false;

  var interval = window.setInterval(function() {
    if (blocked) {
      document.location.href = document.location.href + '#' + Math.random();
      blocked = false;
    }
  }, 100);

  window.addEventListener('beforeunload', function () {
      blocked = true;
  }, false);

  window.addEventListener('unload', function () {
      blocked = false;
  }, false);
})();

The page will never leave.