I tried the code on Chrome, FireFox and Safari. Still the onbeforeunload does not fire. I also tried the onunload, but it did not work.
Here is the code I am experimenting with:
<!doctype html>
<html lang="en">
<head>
<title> Output to a Page </title>
<meta charset="utf-8">
<script>
window.onload = init;
window.onclick = clk;
window.onbeforeunload = closing;
function clk() {
window.alert("Ouch !!");
}
function closing() {
console.log("function alrt WORKS !!!!");
window.alert("closing now.....");
}
function init() {
var output = "";
for (var mms = 5; mms > 0; mms--) {
if (mms >= 3) {
output += "Still lots of M&Ms left, so eat more!<br>";
} else {
output += "Getting low on M&Ms, take it easy!<br>";
}
}
output += "All out of M&Ms";
var e = document.getElementById("output");
e.innerHTML = output;
}
</script>
</head>
<body>
<p id="output"></p>
</body>
</html>
Onbeforeunload is subject of one of bigest missunderstanding in the webdevelopers world :D
1) It refuses to call all blocking native functions (alert, prompt, confirm). It is obvious from User perspective.
2) it (according to MDN) should be registered by "addEventListener" (MDN)
3) It is fired only if there was ANY interaction of the user with the site. Without ANY interaction (even one click anywhere) event onbeforeunload won't be fired.
4) The aim of this event IS eg. secretly saving data left in forms (or else) on behalf of user (or logging user behavior etc.). It is NOT for blocking refreshing the site !
Thus there is no way (because it would be for nothing) to show personalised information.
The only sens is to hide the prompt window while reloading with prior saveing data.
5) If you want to hide the prompt window just NOT set any value for the event.returnValue field.
This example unload site (writing on console text "UNLOAD:1") without window prompt during refresh.
window.addEventListener("beforeunload", function(event) {
console.log("UNLOAD:1");
//event.preventDefault();
//event.returnValue = null; //"Any text"; //true; //false;
//return null; //"Any text"; //true; //false;
});
This example unload site (writing on console text "UNLOAD:1") WITH window prompt during refresh.
window.addEventListener("beforeunload", function(event) {
console.log("UNLOAD:1");
//event.preventDefault();
event.returnValue = null; //"Any text"; //true; //false;
//return null; //"Any text"; //true; //false;
});
You can use any kind of value to event.returnValue (as listed on the right). It is just coding style matter.
Both event.preventDefault nor return has no influence on this event (so in your code you can omit those commented lines).
Tested on Chrome, Edge, Firefox, Opera (verified on 23.09.2019). Hope it helps.
[EDIT:]
To avoid reloading mobile application by accidentally swipe/drag of the screen (eg. google maps, images and any other stable content) this css trick can be usefull:
body {
overscroll-behavior-y: contain !important;
}
The application will be safe against reloading.
It is woth to consider to give to user another possibilty (eg. some button) to reload if needed.
The onbeforeunload event is not cancel-able, because of security reasons, but if an event handler function for the onbeforeunload event returns a string value, this text will be shown in a confirmation dialog box, where the user can confirm whether he wants to stay or leave the current page.
Note that event listeners cannot be registered for the onbeforeunload event with the addEventListener and attachEvent methods (only Safari and Google Chrome support it). For a cross-browser solution, register the event handler in HTML (with the onbeforeunload attribute of the body element) or with the onbeforeunload in-line event property of the window object. See the examples below for details.
Examples:
In HTML:
<ELEMENT onbeforeunload="handler">
In JavaScript:
object.onbeforeunload = handler;
object.addEventListener ("beforeunload", handler, useCapture);
Actions that invoke the onbeforeunload event:
Navigating to another page directly in the browser or via a link.
Closing the current browser window or tab page.
Reloading the current page.
Manipulating the URL of the currently loaded page through the location object from JavaScript.
Invoking the window.navigate method.
Invoking the window.open or the document.open method to open a document in the same window.
Try to modify your code, like this:
window.onbeforeunload = closing;
/* other code here */
var closing = function () {
console.log("function alrt WORKS !!!!");
window.alert("closing now.....");
}
...or just put directly the code in your body tag:
<body onbeforeunload="alert('function alrt WORKS !!!!')">
See here and here for more details.
I faced problem where neither beforeunload nor onunload worked to execute one ajax call that should get called when user closes the browser. In fact, none of the methods worked. The javascript method was inside the body tag, which was actually the problem. It was magically solved when I moved the javascript method inside Head tag.
For people who are experiencing this issue in certain browsers (Safari in my case), after some research, I realized that it was because of how the browser works. This post has a more detailed explanation.
Basically, what I did was to use the alternative which is onpagehide, and so far it works with all browsers that I have tested.
Related
I've used the event in other projects/games but it doesn't seem to be working on this one. onload event is working fine tho.
Script is linked on the bottom of the html before the < /body > tag
the code in client.js
(() => {
// Player Closes window
window.addEventListener("beforeunload", function (e) {
sock.emit('player-leave', player);
alert('window.addEventListener');
});
window.onbeforeunload = function(event) {
sock.emit('player-leave', player);
alert('window.onbeforeunload');
};
window.onunload = function(event) {
sock.emit('player-leave', player);
alert('window.onunload');
};
})();
Event doesn't pass throu and no alert is shown.
Link to git repository for full code: https://github.com/Tw1ster95/drawitgame
EDIT: I guess i found a way to use the socket id for the disconnect of player but i'm still wondering why doesn't it emit on beforeunload.
It is not the problem of onbeforeonload. The reasons why alert doesn't work is because modern browser will ignore the alert() when doing beforeunload.
The HTML specification states that calls to window.alert(),
window.confirm(), and window.prompt() methods may be ignored during
beforeunload event. See the HTML specification for more details.
Check it here
If you run your webpage and keep pressing a reloading key, you may able to see the error message Blocked alert() when beforeunload in the console.
Tried to call browser tab close event when click on close tab icon in chrome browser but not working.I want to show alert message before close the browser tab.How do it?
Below code is not working:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<script type="text/javascript">
window.onbeforeunload = function(evt) {
var message = "Are you sure?";
/* InternetExplorer/Firefox*/
var e = evt || window.event
e.returnValue = message
/* WebKit browser */
return message;
}
</script>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
In some browsers, calls to window.alert(), window.confirm(), and
window.prompt() may be ignored during this event. See the HTML
specification for more details.
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
Try a console.log and check "Preserve Log" in your Console. You will see that it's just alert() that doesn't work in your case
You are in fact correctly detecting the tab close event! The problem is with your triggered action. From the relevant MDN documentation:
To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all.
This means that it's going to be very difficult for you to show an alert message before closing the browser tab as you say you want do you. You can however achieve something similar by using the return value on the handler. Again quoting from the documentation:
When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string.
See this other question Warn user before leaving web page with unsaved changes for more details.
To prevent Scam, Browsers are cautios with those messages. Most are very limited in what you can do. Chrome shows the standardized message "Leave Site? Changes that you made may not be saved." which is not changable afaik. To achieve this, simply use:
window.onbeforeunload = function () {
return true;
};
An alternative to that is to detect when the mouse is leaving the window. That is not the same, but often leaving the viewport is the action taken before closing a tab. You can detect the event when the mouse leaves the window and trigger whatever message or pop up you like. I personally find that very annoying though.
I want to capture the browser window/tab close event. I have tried the following But not working:
<script type="text/javascript">
window.onbeforeunload = function(){ myUnloadEvent(); }
function myUnloadEvent() {
alert ('Calling some alert messages here');
}
</script>
<body>
Body of the page goes here.
</body>
Tried these links also but no more success.
javascript to check when the browser window is close
How to capture the browser window close event?
javascript detect browser close tab/close browser
Trying to detect browser close event
Problem :
I just want to detect the browser close event and do some handling on that without showing the prompt to the user.
I have tried many methods to detect browser close event through jQuery or JavaScript. But unfortunately I could not succeed. The onbeforeunload and onunload methods are also not working.
Any help will be highly appreciated. Thanks
You cannot show an alert() on an onbeforeunload. You need to return to show a confirm dialog.
<script type="text/javascript">
window.onbeforeunload = function(e){
return 'Calling some alert messages here'; //return not alert
}
</script>
<body>
Body of the page goes here.
</body>
Also do not call a function like that, write directly in the onbeforeunloadOR return myUnloadEvent(); It depends what you are trying to do inside onbeforeunload. Try not to make any AJAX call as the browser may not run the script. You can unset web storage varibles, delete session, etc.
Also beware that this event will also fire when you refresh the page.
You can see the console quickly write that line before the screen closes.
window.onbeforeunload = myUnloadEvent;
function myUnloadEvent() {
console.log("Do your actions in here")
}
Alerts are not allowed during beforeunload - if you have Preserve log switched on you will see this:
Blocked alert('Calling some alert messages here') during beforeunload.
But if you use a console.log command, it will go through.
I have a form where the input fields are saved onChange. In Firefox (5) this works even when the window is closed, but for Chrome and IE it doesn't and I need to be sure that I'm saving this data even if they try to close the window after they've typed in a field but an onBlur event hasn't occurred (i.e. they've typed something into a textbox, but haven't tabbed out of it).
I have read the following SO articles on using window.onbeforeunload:
article 1
article 2
if I use the following:
window.onbeforeunload = function() {
return "onbeforeunload";
}
then I get a popup with onbeforeunload in.
but if I try:
window.onbeforeunload = function() {
alert("onbeforeunload");
}
then nothing happens in any browser, even Firefox.
what I want to achieve is:
window.onbeforeunload = function() {
saveFormData();
}
I'd be grateful if someone could point out where I might be going wrong.
You have to return from the onbeforeunload:
window.onbeforeunload = function() {
saveFormData();
return null;
}
function saveFormData() {
console.log('saved');
}
UPDATE
as per comments, alert does not seem to be working on newer versions anymore, anything else goes :)
FROM MDN
Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.
It is also suggested to use this through the addEventListener interface:
You can and should handle this event through window.addEventListener() and the beforeunload event.
The updated code will now look like this:
window.addEventListener("beforeunload", function (e) {
saveFormData();
(e || window.event).returnValue = null;
return null;
});
There seems to be a lot of misinformation about how to use this event going around (even in upvoted answers on this page).
The onbeforeunload event API is supplied by the browser for a specific purpose: The only thing you can do that's worth doing in this method is to return a string which the browser will then prompt to the user to indicate to them that action should be taken before they navigate away from the page. You CANNOT prevent them from navigating away from a page (imagine what a nightmare that would be for the end user).
Because browsers use a confirm prompt to show the user the string you returned from your event listener, you can't do anything else in the method either (like perform an ajax request).
In an application I wrote, I want to prompt the user to let them know they have unsaved changes before they leave the page. The browser prompts them with the message and, after that, it's out of my hands, the user can choose to stay or leave, but you no longer have control of the application at that point.
An example of how I use it (pseudo code):
onbeforeunload = function() {
if(Application.hasUnsavedChanges()) {
return 'You have unsaved changes. Please save them before leaving this page';
}
};
If (and only if) the application has unsaved changes, then the browser prompts the user to either ignore my message (and leave the page anyway) or to not leave the page. If they choose to leave the page anyway, too bad, there's nothing you can do (nor should be able to do) about it.
The reason why nothing happens when you use 'alert()' is probably as explained by MDN: "The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event."
But there is also another reason why you might not see the warning at all, whether it calls alert() or not, also explained on the same site:
"... browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with"
That is what I see with current versions of Chrome and FireFox. I open my page which has beforeunload handler set up with this code:
window.addEventListener
('beforeunload'
, function (evt)
{ evt.preventDefault();
evt.returnValue = 'Hello';
return "hello 2222"
}
);
If I do not click on my page, in other words "do not interact" with it, and click the close-button, the window closes without warning.
But if I click on the page before trying to close the window or tab, I DO get the warning, and can cancel the closing of the window.
So these browsers are "smart" (and user-friendly) in that if you have not done anything with the page, it can not have any user-input that would need saving, so they will close the window without any warnings.
Consider that without this feature any site might selfishly ask you: "Do you really want to leave our site?", when you have already clearly indicated your intention to leave their site.
SEE:
https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
I seem to be a bit late to the party and much more of a beginner than any expertise; BUT this worked for me:
window.onbeforeunload = function() {
return false;
};
I placed this as an inline script immediately after my Head and Meta elements, like this:
<script>
window.onbeforeunload = function() {
return false;
}
</script>
This page seems to me to be highly relevant to the originator's requirement (especially the sections headed window.onunload and window.onbeforeunload):
https://javascript.info/onload-ondomcontentloaded
Hoping this helps.
you just cant do alert() in onbeforeunload, anything else works
To pop a message when the user is leaving the page to confirm leaving, you just do:
<script>
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave this page? You will lose any unsaved data.';
};
</script>
To call a function:
<script>
window.onbeforeunload = function(e) {
callSomeFunction();
return null;
};
</script>
Yes what everybody says above.
For your immediate situation, instead of onChange, you can use onInput, new in html5. The input event is the same, but it'll fire upon every keystroke, regardless of the focus. Also works on selects and all the rest just like onChange.
I have written this code
function winUnload() {
alert("Unload Window");
MyMethod();
}
window.onunload = function() { winUnload(); }
This code is working fine in IE and Firefox. But this code is not working in Chrome. Both the statements alert("Unload Window"); and MyMethod(); are not working.
There are some actions which are not working in chrome, inside of the unload event. Alert or confirm boxes are such things.
But what is possible (AFAIK):
Open popups (with window.open) - but this will just work, if the popup blocker is disabled for your site
Return a simple string (in beforeunload event), which triggers a confirm box, which asks the user if s/he want to leave the page.
Example for #2:
$(window).on('beforeunload', function() {
return 'Your own message goes here...';
});
Demo: http://jsfiddle.net/PQz5k/
I know this is old but I found the way to make unload work using Chrome
window.onbeforeunload = function () {
myFunction();
};
Armin's answer is so useful, thank you. #2 is what's most important to know when trying to set up unload events that work in most browsers: you cannot alert() or confirm(), but returning a string will generate a confirm modal.
But I found that even with just returning a string, I had some cross-browser issues specific to Mootools (using version 1.4.5 in this instance). This Mootools-specific implementation worked great in Firefox, but did not result in a confirm popup in Chrome or Safari:
window.addEvent("beforeunload", function() {
return "Are you sure you want to leave this page?";
});
So in order to get my onbeforeonload event to work across browsers, I had to use the JavaScript native call:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page?";
}
Not sure why this is the case, or if it's been fixed in later versions of Mootools.
You may try to use pagehide event for Chrome and Safari.
Check these links:
How to detect browser support for pageShow and pageHide?
http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
Please try window.onbeforeunload instead for window.onunload for chrome.
You can also try calling onbeforeunload from the body> tag which might work in chrome.
However, we do have a problem with unload function in chrome browser.
please check
location.href does not work in chrome when called through the body/window unload event
The onunload event won't fire if the onload event did not fire. Unfortunately the onload event waits for all binary content (e.g. images) to load, and inline scripts run before the onload event fires. DOMContentLoaded fires when the page is visible, before onload does. And it is now standard in HTML 5, and you can test for browser support but note this requires the <!DOCTYPE html> (at least in Chrome). However, I can not find a corresponding event for unloading the DOM. And such a hypothetical event might not work because some browsers may keep the DOM around to perform the "restore tab" feature.
The only potential solution I found so far is the Page Visibility API, which appears to require the <!DOCTYPE html>.
This works :
var unloadEvent = function (e) {
var confirmationMessage = "Warning: Leaving this page will result in any unsaved data being lost. Are you sure you wish to continue?";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome etc.
};
window.addEventListener("beforeunload", unloadEvent);