Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

This is my code:

<!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>

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

Thanks!


ANSWER: Don't test the unload event with alerts ;)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
638 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...