javascript to check when the browser window is closed - javascript

Does anyone know any way that I can use javascript to check when the browser window is closed and pop-up a confirmation dialog to ask whether the user is confirm to exit the browser or change his mind to stay?

window.onbeforeunload = function (e) {
var e = e || window.event;
//IE & Firefox
if (e) {
e.returnValue = 'Are you sure?';
}
// For Safari
return 'Are you sure?';
};
https://developer.mozilla.org/en/DOM/window.onbeforeunload

The documentation here encourages listening to the onbeforeunload event and/or adding an event listener on window.
window.addEventListener('beforeunload', function(e) {}, false);
You can also just populate the .onunload or .onbeforeunload properties of window with a function or a function reference.
Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.

If the browser remains running after the page is closed, and if the browser processes the "onbeforeunload" event of the body element (sometimes it's disabled), and if the browser allows popup windows or mesage boxes and the ability to return false from that event to prevent the page change, then it's possible.
For an example, start typing a comment on any stackoverflow page with Javascript enabled and then navigate away from that page.

This worked for me:
function closeWin(){
var exit = confirm("Do you want to leave this window?");
if(exit==true){
//do something before closing;
}
}
body onbeforeunload="closeWin()"

This works too, unless for IE8
$(window).bind('beforeunload', function (e) {
// code to execute when browser is closed
e.$.post("func.php", { action: 'action', id_userMsg: '<?php echo $id_user; ?>' });
});

Related

My requirement is that I want to show a message to user while closing the browser tab or window

I am trying using following code-
window.onunload = function(e){
return "Do you really want to quit without saving."
}
**
But message is also appearing if I will try to navigate from one page
to another
**. I only want this functionality if user clicks on the [x] button not on any event change.
I have also tried following-
window.onbeforeunload = function(e){
return "Somethig"
}
Note- I want to identify the event when user only closing the browser, not for any other page event.
Using Jquery:
$(window).unload(function() {
//your code
});
using javasscript:
window.onbeforeunload = function(e){
var displaymessage = 'Are you sure?';
e = e || window.event;
if(e)
e.returnValue = displaymessage;
return displaymessage;
}
This question is a duplicate of this question.
You can't modify the default dialogue for onbeforeunload, so your best bet may be to work with it.
Also, in recent versions of Chrome, the feature has been deprecated.
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)

Execute Javascript function before browser reloads/closes browser/exits page?

Is there a way to execute a function before a user chooses to reload/close browser/exit page?
I need this for an "online/offline" status function i am trying to write. I want to detect whether the user is still on the page or not.
Any ideas? :)
Maybe there is a better approach to this?
Inline function:
window.onbeforeunload = function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
};
or via an event listener (recommended):
window.addEventListener("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
or if you have jQuery:
$(window).on("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
Notes:
When this event returns a non-void value, the user is prompted to
confirm the page unload. In most browsers, the return value of the
event is displayed in this dialog.
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.
See documentation at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
Use window.onbeforeunload, it is triggered when user leaves your page :http://geekswithblogs.net/hmloo/archive/2012/02/15/use-window.onbeforeunload-event-to-stop-browser-from-closing-or-disable.aspx
Try this:
$( window ).unload(function() {
alert( "Handler for .unload() called." );
});
OR this if you want conformation alert
<script>
window.onbeforeunload = function(e) {
return 'Your dialog message';
};
</script>

How to handle browser's window.onbeforeunload event

I want to handle window.onbeforeunload event. I can handle it this way
window.onbeforeunload = function() {
return "MSG";
}
But in this case it shows a popup asking for user confirmation i dont want that confirmation dialog instead it will directly return false like event.cancel = true.
You cannot do this in the onBeforeUnload. The for this reason is; the user has already sent in a request to move away from the page and the event has been intercepted. The confirm is the best you can do, unless you prevent the event further up the event chain (such as with onkeydown).
For instance, if you want the user to not be able to use their keyboard to go backwards and forwards in history, or to reload the page, this could be achieved using;
var catchKey = {
37: true, /// left
39: true /// right
};
window.onkeydown = function(event) {
if (catchKey[event.keyCode] && event.ctrlKey) {
event.preventDefault();
event.stopPropagation();
}
}
Hope that helps!
Basically you want to prevent the user from closing the browser window/tab or navigate away from your page at all?
I am sure no browser maker will let you do that... then the only way to close the browser in such a case would be to kill the process.
So: Not possible, as far as I can see.

I want to call function on window unload

I am trying to display confirmation box using window.confirm on window unload event.
If a user clicks on the OK button on confirmation box then I want to call one function and if user clicks the CANCEL button then window should be get closed.
My code is:
<script>
function confirmit(){
var result=window.confirm("Are you sure?");
if(result) {
// close all child windows
} else{
// window should not get close
}
}
</script>
<body onunload='confirmit();' >
But the problem is if I click on CANCEL button, window is getting closed.
Please help me.
You can't prevent unload to stop the page from unloading. You need to bind to onbeforeunload instead. You should just return the string you want to display to the user from the event handler (note that in some browsers the string may not be displayed)
<script type="text/javascript">
window.onbeforeunload = function(e){
var msg = 'Are you sure?';
e = e || window.event;
if(e)
e.returnValue = msg;
return msg;
}
</script>
More info here
JSFiddle Example here
change your code to this to make it work cross-browser:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Do you really want to exit?';
}
// For Safari
return 'Do you really want to exit?';
};
</script>
<body>
...
note that this is using the onbeforeunload-event (more information / view an example) where the return-value has to be the message that should be shown to the user.
i don't know if you'll have a chance to react on the confirmation to do something after that (closing child-windows for example), but i don't think so.

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.
This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.
<script type="text/javascript">
var onBeforeUnloadFired = false;
window.onbeforeunload = function ()
{
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
</script>
Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.
This is definitely a FF bug. I've reported it at https://bugzilla.mozilla.org/show_bug.cgi?id=531199
The best solution I've found is to use a flag global variable that is reset after so many milliseconds, say 500 (this ensures that the function can be called again, but not immediately after its appearance).
See last code in:
http://social.msdn.microsoft.com/Forums/en/sharepointinfopath/thread/13000cd8-5c50-4260-a0d2-bc404764966d
I've found this problem in Chrome 21, Firefox 14, IE 7-9, Safari 5 (on PC).
The following works on all of these browsers. If one removes the window.onbeforeunload function during the event this will prevent the second call. The trick is to reset the window.onbeforeunload function if the user decides to stay on the page.
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// #uses window_on_before_unload
// #param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();
Create a global variable that is set to true inside the handler. Only show the alert/popup when this variable is false.
I use the following snippet to track the exitcount
When the page loads the following variable exitCount is initialized
if (typeof(MTG) == 'undefined') MTG = {};
MTG.exitCount=0;
and in the Window unload event
$(window).bind("beforeunload", function(){
if (MTG.exitCount<=0)
{
//do your thing, save etc
}
MTG.exitCount++;
});
I've found that instead of doing your own call to confirm(), just do even.preventDefault(); within the beforeunload event. Firefox throws up its own confirm dialog.
I'm not sure if this is the correct/standard thing to do, but that's how they're doing it.
I have a document opening another popup window with window.open. In the original window I have registered (with jquery) a listener for "unload" event like this:
var popup_window = window.open(...)
$(popup_window).on('unload', function(event) ...
I have came across this page because the event was effectively triggering twice. What I have found is that it is not a bug, it triggers twice because it fires once for "about:blank" page being replaced by your page and another for your page being unloaded.
All I have to do is to filter the event that I am interested in by querying the original event:
function (event) {
var original_url = e.originalEvent.originalTarget.URL;
if (original_url != 'about:blank')
{
... do cool things ...
}
}
I don't know if this applies to the original question, because it is a special case of a window opening another, but I hope it helps.

Categories