Event to be triggered when leaving website or closes the browser - javascript

I´m trying for a while execute a JavaScript function when a user leaves web site by typing a address in the browser and hits return or the user closes the browser clicking in the x button.
I tried the unload event but I cannot get the alert.
This is what I am doing:
$(window).unload(function () {
alert("Are you sure?");
});
also
$(body).unload(function () {
alert("Are you sure?");
});
I am running out of ideas!

You can listen to beforeunload event that fires before the unload event, when the page is unloaded.
$(window).on('beforeunload', function(){
// ...
})

Some browsers (like Chrome) block alerts in unload event handlers, to prevent exactly these kind of annoying messages. Try a console.log or put a breakpoint in to find out if the handler is triggered when you don't have an alert there.
SO question on a similar line:
window.onunload is not working properly in Chrome browser. Can any one help me?
You can only pass the alert by returning a string in a beforeunload handler (HT #undefined), but I would avoid even that, because popups are generally bad, and most people will do minimum processing to work out the make-this-thing-go-away option before they actually think about the contents of the box.

The function you defined in window.onbeforeunload if it returns a string it will pop up a confirm navigation prompt with that message.
Alerts may be ignored!
window.onbeforeunload = function() {
return "All unsaved data will be lost. Are you sure?";
};
Some browsers handle the onbeforeunload differently. Recent Firefox for example will ignore your return string and just display a standard message.

$(window).bind('beforeunload', function(){
alert("Are your sure?")
});

Related

Mobile browser Back button event handling

When i click Mobile browser back button, It should say the confirmation box like
"Are you wants to leave this page"
If the user click "OK" I need to trigger some function.
It's working fine. But when i click "Cancel" it's not staying on the same page. I tried the below code. But am not able to success.
var unloadEvent = function (e) {
var confirmationMessage = "Are you want to leave this page";
(e || window.event).returnValue = confirmationMessage;
if(confirm(confirmationMessage)) {
//some JS function
} else {
return false;
}
};
window.addEventListener("beforeunload", unloadEvent);
Please help me to solve this issue.
Thanks
You can't modify the default dialogue for onbeforeunload, so your best bet may be to work with it.
window.onbeforeunload = function() {
//Do some other stuff here..
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
When onbeforeunload is called, it will take the return value of the handler as window.event.returnValue.
It will then parse the return value as a string (unless it is null).
Since false is parsed as a string, the dialogue box will fire, which will then pass an appropriate true/false.
The result is, there doesn't seem to be a way of assigning false to onbeforeunload to prevent it from the default dialogue.
Additional notes on jQuery:
Setting the event in jQuery may be problematic, as that allows other onbeforeunload events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.
jQuery doesn't have a shortcut for onbeforeunload so you'd have to use the generic bind syntax.
$(window).bind('beforeunload', function() {} );
This answer is suggested by Owen on the question: override onbeforeunload
Thanks Owen.

Different actions with onbeforeunload

I am working on a simple chat script using Ajax and want to indicate when a user leaves the page. Have read several docs and found this works:
window.onbeforeunload = leaveChat;
function leaveChat(){
... my code
return 'Dont go...';
}
Unfortunately (and logically), if they cancel the exit, my code is still executed and they are flagged as leaving even though they are still on the page? It should only execute if the confirm leaving the page. Any suggestions?
I would use onunload, but it doesn't seem to work in any of my browsers (Chrome, IE).
First, you should add the event handler using:
window.addEventListener('beforeunload', function() {
// Confirmation code here
});
window.addEventListener('unload', function() {
// fire pixel tag to exit chat on server here
// UI interactions are not possible in this event
});
For further research:
unload event reference
beforeunload event reference
Window.onunload reference

Is it possible to capture the user's answer when using onbeforeunload confirmation?

I need to warn users that they will lose information when leaving a page. This is easily done using the onbeforeunload event. My problem is that I want to take some action if the user decides to leave.
Here's an example (I'm using jquery because it's loaded anyway):
$(window).on('beforeunload', function(e){
return "Do you really want to leave?";
});
What I would like to do is something like this (this code doesn't work, I know, it's just an example to illustrate what I'm trying to do):
$(window).on('beforeunload', function(e){
// Ask for user confirmation
var bUserAnswer = confirm("Do you really want to leave?");
if(bUserAnswer)
{
// Do something...
}
else
{
// Do something else...
}
// Close everything if the user decides to leave...
return bUserAnswer;
});
I have no idea if what I'm trying to do here is even possible... Googling around didn't give me any indication one way or the other so I'm turning to my favorite group of experts!
Any idea how I could do it?
Thanks!
When leaving the page, the events beforeunload and unload execute, in that order. Of course, if the beforeunload event doesn't complete, the unload event won't.
The way the beforeunload event doesn't complete is when the user clicks the "Stay on Page" button instead of "Leave Page" (if that dialog is presented to them, like in your code).
So if you know that the possibility for them to not leave the page will always be presented to them, the only way for the unload event to execute is if the beforeunload event isn't prevented (by the user).
Therefore, you should be able to put any code that you want to execute when the user actually chooses to leave the page in the unload event.
As for knowing if the user decided to stay on the page, I'm not sure how to catch it :)
window.addEventListener('beforeunload', this.handleUnload);
window.addEventListener("unload", function(event) {
//calling ajax or do something here
});
handleUnload (e) {
var message = "your custom message here";
(e || window.event).returnValue = message; //Gecko + IE
return message;
}

Removing the prompt box onbeforeunload [duplicate]

How can I remove prompt on unload event using javascript? thanks in advance...
hm, I don't want to show the prompt when firing the custom function for the unlaod event of the body... Is it possible? so here's my code:
window.onbeforeunload = function()
{
//cancel the unload
//cancel prompt
}
Make sure your event handler doesn't have a return statement in it. Returning from the function triggers the conformation message.
Update based on the code comments in the edited question: If the user does something to leave the page, then you can tell the browser to ask them if they are sure. You cannot silently prevent them. If the user wishes to leave the page, then they can do so (dodgy sites full of adverts and/or malware would love it to be otherwise, thankfully it isn't)
Most certainly NOT impossible. All you have to do to suppress the prompt is omit the "return" statement. Returning any value will cause the prompt to fire. Example:
window.onbeforeunload = function saveAllData()
{
//Invoke AJAX method to save DataTable in database
[classname].SaveDataTable();
//return true; //comment out 'return' to suppress prompt
}
function SaveDataTable_Callback(response)
{
//alert(response);
}

How to remove prompt on unload event using javascript

How can I remove prompt on unload event using javascript? thanks in advance...
hm, I don't want to show the prompt when firing the custom function for the unlaod event of the body... Is it possible? so here's my code:
window.onbeforeunload = function()
{
//cancel the unload
//cancel prompt
}
Make sure your event handler doesn't have a return statement in it. Returning from the function triggers the conformation message.
Update based on the code comments in the edited question: If the user does something to leave the page, then you can tell the browser to ask them if they are sure. You cannot silently prevent them. If the user wishes to leave the page, then they can do so (dodgy sites full of adverts and/or malware would love it to be otherwise, thankfully it isn't)
Most certainly NOT impossible. All you have to do to suppress the prompt is omit the "return" statement. Returning any value will cause the prompt to fire. Example:
window.onbeforeunload = function saveAllData()
{
//Invoke AJAX method to save DataTable in database
[classname].SaveDataTable();
//return true; //comment out 'return' to suppress prompt
}
function SaveDataTable_Callback(response)
{
//alert(response);
}

Categories

Resources