window.onbeforeunload handling ok and cancel options - javascript

I have a window.onbeforeunload function which generates the default message:
"Are you sure you want to navigate away from this page...." .
If we click on OK we are redirected to a new link and if we press cancel we are redirected back to the same page.
I want to save some data from the page when we press OK and move away from the page. How can we know if OK or cancel has been pressed, then make an event call and continue with the "ok"/"cancel" option.

A possible approach might be to hook into the onunload event as well, and if that handler is called, you know that the user chose OK.
In onbeforeunload, set a timeout callback that is called some time afterwards (e.g. 1 second), and if it is called, the user might have selected Cancel.
Not sure how safe this is regarding race conditions though.

function leavePage() {
//do your thing like saving the data in the session
return "Some data entered may be lost."; //a text needs to be returned
}
window.onbeforeunload = leavePage;

Are you using JavaScript 'confirm' dialog?
if(confirm("Are you sure you want to navigate away from this page....")) {
// OK was pressed
} else {
// Cancel was pressed
}

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.

Correct way to unset submit button text now that Jquery's .unload is deprecated

SETUP - Large search with many criteria as a POST via a html submit button, it can take several seconds before the first byte is sent by the server / results page starts loading.
http://api.jquery.com/unload/ is now deprecated (as of version 1.8), and I'm searching for the CORRECT way to do the following...
When someone clicks the search button, I give the user a little feedback by setting the button text to "Searching...", then allow the submit to continue (return true):
$('#dosearch').click(function() {
$(this).html('<i class="icon-spinner icon-spin"></i> Searching...');
return true;
});
During unload I'm currently doing this:
$(window).unload(function() {
$('#dosearch').html('<i class="icon-search"></i> Search');
});
I tried binding to beforeunload, but that fires as soon as the submit happens (bad), not as soon as the browser begins rendering the new page (good).
The problem is if they click search and then click the BACK button on their browser. If they do that, then the Searching... text is still shown.
What is the correct / proper way to do what I'm attempting here?
NOTE: (The reason for the I tag is that I'm using font awesome).
Binding an empty event handler to unload seems to work, but it's kind of a hack.
$('#dosearch').click(function() {
$(this).html('<i class="icon-spinner icon-spin"></i> Searching...');
return true;
});
$(window).on("load", function(){
$('#dosearch').html('<i class="icon-search"></i> Search');
});
$(window).on("unload", function(){
// Leave this blank handler here or onload won't fire on IE or FF when you click back button
});
See this question for explanation.
If the user goes back in history, it means it renders the page new or not? So you could, whenever the page is loaded, reset the value to what you want to.
Could that be something?

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;
}

onbeforeunload not working within unload

I have wrote the following code to run the onbeforeunload within unload. However, this doesn't seem working. Does anyone know what's wrong about my code and anyway to make it work?
$(window).unload(function () {
if ($('.submitAction').val() == "" && isChange) {
window.onbeforeunload = confirmExit;
}
});
function confirmExit() {
return "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?";
}
The onunload event is the absolute last event that fires when the user navigates away from the page or closes the browser.
Binding to the onbeforeunload event within the onunload event would be pointless, as this event has already occurred (hence the name onbeforeunload). The solution would be to bind to the onbeforeunload event before the event actually happens, such as when the page loads.
Something like this (untested):
$(window).bind('beforeunload', function () {
if ($('.submitAction').val() == "" && isChange) {
return "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?";
}
});
This line returns a string:
return "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?";
I think you meant:
return window.confirm("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?");

Confirm browser back button else stay on page

In javascript or jquery I need to add an alert when the user clicks on the browser back button that has an ok/cancel button model, but instead of "Ok" it should say Leave and instead of Cancel it should say Stay. Thanks
You can't control the confirmation dialog button text, it's a hard coded feature of confirm() and is whatever the browser has...not much you can do about it.
For the actual display you can use window.onbeforeunload, but it won't be specific to the back button, any action leaving the page will trigger this, for example:
window.onbeforeunload = function() {
return "Are you sure you wish to leave this delightful page?";
}

Categories

Resources