Reputation: 3447
I have this code:
(function() {
window.onbeforeunload = function () {
alert("hi")
console.log("unloading");
};
})();
I also have this code:
window.addEventListener("beforeunload", function() {
alert("hi")
console.log("unloading")
});
None of them seem to work. All I want to do is log when the user tries to leave the page, but this isn't happening (latest Chrome, latest Firefox, Edge....), can anybody shed some light on why it's not working?
Upvotes: 3
Views: 7616
Reputation: 316
You have to return from the onbeforeunload:
(function() {
window.onbeforeunload = function () {
alert("hi")
console.log("unloading");
return null;
};
})();
Upvotes: 0
Reputation: 12085
function myFunction() {
return "Write something clever here...";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onbeforeunload="return myFunction()">
</body>
Upvotes: 0
Reputation: 1669
Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details. Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded.
Also, use return
statement to prompt user before leaving
window.addEventListener("beforeunload", function() {
return "hi";
});
Upvotes: 3
Reputation: 4346
Do it this way:
window.onbeforeunload = function (e) {
console.log("unloading");
return "Hi";
};
That will alert Hi
when page unloads and also prints unloading
in console
Upvotes: 0