Detect if browser goes to another page

I need to check if the browser is moving to another page or is closing. My idea:

  • Create a global variable var isNavigating = false;
  • Bind a click event to make isNavigating = trueeach anchor jump to a different page
  • Verify that isNavigatingtrue on the body of the unloadevent.

Any other ideas? Recommendations?

+5
source share
2 answers

You can do this with the following script.

<script type="text/javascript"> 
     window.onbeforeunload = function(){ return;} 
</script> 

However, if you plan to cancel the navigation, just do not worry. As far as I know, this is not possible.


The code below checks if the user clicked the link.

var checkAnchorClick = false;

$(document).ready(function () {
    $("a").live("click", function () {
        checkAnchorClick = true;
    });
});

$(window).unload(function () {
    if (checkAnchorClick)
        alert("User clicked a link...");
    else
        alert("Something else...");
});
+7
source

Just bind windows to the onunload event.

0
source

All Articles