我无法在Chrome中触发卸载事件 [英] I can't trigger the unload event in Chrome

查看:75
本文介绍了我无法在Chrome中触发卸载事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码在Firefox上运行良好,但我无法让Chrome上的卸载事件工作。 Chrome是否停止支持卸载活动了?

This code runs fine on Firefox, but I can't make the unload event work on Chrome anymore. Did Chrome stop supporting the unload event?

这是我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>

<script type="text/javascript" src="../jquery/jquery.js"></script>

<script type="text/javascript">

    function pageHidden(evt) { alert("Are you sure 1?"); } //WORKS ON FIREFOX BUT NOT IN CHROME
    window.addEventListener("pagehide", pageHidden, false);

    window.onunload = function () { alert("Are you sure 2?"); } //TRIGGERS ON LOAD NOT ON UNLOAD

    $(window).unload(function () { //WORKS ON FIREFOX BUT NOT IN CHROME
        alert("Are you sure 3?");
    });

</script>
</head>

<body>
TEST WEBSITE
<a href="http://www.iamawesome.com">external link</a>
</body> 
</html>

如何让unload事件在Chrome中运行?

How can I get the unload event to work in Chrome?

谢谢!

答案:
不测试卸载事件警报;)

推荐答案

window.onunload = alert("Are you sure 2?");

这是不正确的。您将 onunload 设置为 alert 的结果,您需要将其设置为函数:

This is incorrect. You are setting onunload to the result of alert, you need to set it to a function:

window.onunload = function(){
    alert("Are you sure?");
}

如果你想使用jQuery,这将适用于所有浏览器。

If you want to use jQuery, this will work in all browsers.

$(window).unload(function () {
     alert("Are you sure?");
});

注意:它可能似乎就像它的不在Chrome中工作,但确实如此。那是因为Chrome会在 onunload 事件中阻止 alert

NOTE: It might seem like it's not working in Chrome, but it is. That's because Chrome blocks alerts in the onunload event.

这篇关于我无法在Chrome中触发卸载事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆