最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detecting if browser navigating to another page - Stack Overflow

programmeradmin4浏览0评论

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? Remendations?

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? Remendations?

Share Improve this question asked Jul 7, 2011 at 14:52 timutimu 8387 gold badges20 silver badges41 bronze badges 2
  • 1 I think you might want to reword your question to make it clear you want to know whether they are navigating away or whether they are closing (i.e. to know which is happening, not just to know either is happening). As it's written just now, it's ambiguous as to whether you want to be able to tell the difference between them or not. – ADW Commented Jul 7, 2011 at 15:10
  • if a user typing a new website in the address bar and hitting enter is navigation, there's no way to tell the difference between that and the user closing the tab. – Thomas Shields Commented Jul 7, 2011 at 15:43
Add a ment  | 

1 Answer 1

Reset to default 13

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...");
});
发布评论

评论列表(0)

  1. 暂无评论