Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if browser navigating to another page

Tags:

javascript

I need to check if browser is navigating to another page or closing. My idea is;

  1. Create global variable var isNavigating = false;
  2. Bind click event to make isNavigating = true of every anchor which will navigate to another page
  3. Check if isNavigating true on body's unload event.

Any other ideas? Recommendations?

like image 900
timu Avatar asked Jul 07 '11 14:07

timu


1 Answers

You can do this by the following script.

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

However if you plan to cancel the navigaion, just don't bother. It's not possible as far as i know.


Code below checks if the user has clicked a 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...");
});
like image 131
Yiğit Yener Avatar answered Sep 20 '22 18:09

Yiğit Yener