javascript 检测浏览器是否导航到另一个页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6612603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:17:06  来源:igfitidea点击:

Detecting if browser navigating to another page

javascript

提问by ümit AKKAYA

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 = trueof every anchor which will navigate to another page
  3. Check if isNavigatingtrue on body's unloadevent.
  1. 创建全局变量 var isNavigating = false;
  2. 绑定点击事件来制作isNavigating = true每个将导航到另一个页面的锚点
  3. 检查isNavigating身体unload事件是否为真。

Any other ideas? Recommendations?

还有其他想法吗?推荐?

回答by Yi?it Yener

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...");
});

回答by Prusse

Just bind to onunload event of the window.

只需绑定到窗口的 onunload 事件。