onbeforeunload not working within unload - javascript

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?");

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.

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

JQUERY click handler from DIFFERENT element triggered on enter?

URL is here: http://prorankstudios.com/sandbox/wtf/
Using IE9, with focus on the User or Pass field, hit the ENTER key...
Notice that this whole page reloads.
What's happening is that the click handler for the #live_site_link (assigned on line 30 of common.js) is running when no click has happened on #live_site_link at all...
Login Submit code:
Login.Submit = function(e)
{
Login.feedback.empty();
if (Login.user.val() == '')
{
Camo.ErrorAlert('Invalid username.',Login.feedback);
Login.user.focus().select();
return false;
}
if (Login.pass.val() == '')
{
Camo.ErrorAlert('Invalid password.',Login.feedback);
Login.pass.focus().select();
return false;
}
Camo.AJAXStart('Logging in...');
postData =
{
user:Login.user.val(),
pass:Login.pass.val()
}
Camo.AJAXPost('index/login/',Login.Success,Login.Failure,postData);
return false;
}
live_site_link click handler:
$('#live_site_link').click(function()
{
window.location.href = './';
});
In fact, the handlers for the login form (both a keyup and a click on Go button assigned in login.js lines 22 and 24 respectively) sometimes run AFTER the page has reloaded, strangely enough.
In IE7/compatibility mode, the keyup and click handlers for login_submit properly work and the page does not reload. This is also the case in all other browsers I tested.
What is IE9 doing?
Try calling e.preventDefault() or e.stopPropagation() before you return false in Login.SubmitOnEnter
It would be better though if you wrapped a form around your form elements, then attached an event for the form submit. That way it will still work without javascript and you wouldn't have to have a separate event for click and enter press.
The only "fix" for this I could figure out short of changing the live site link button to a regular anchor tag was actually to enclose the login fields and button inside form tags.
Apparently without those enclosing form tags, IE9 is using the live_site_link button instead of the GO button to submit the form on a natural enter key press before the keyup handlers on the inputs and the click handler on the Go button of the login form ever get a chance to trigger, which causes the page to reload (as that's what the click handler for live_site_link does).
Now I have to handle logins without AJAX...
You would probably manage the login submittal process easier by using a submit handler rather than needing to catch enter key and make it click on submit button. Seems like extra code to work around doing it a simpler way
$('form').submit(function(){
var valid=someValidionFunction();
return valid;
})
Edited due to no ajax

window.onbeforeunload: Is it possible to get any details about how the window was unloaded?

I'm developing one of those warning windows that tells the user that they may have unsaved data, but I only need it to warn them if they're leaving the page. Currently it does so on refreshes, postbacks, etc. I was wondering if there was any way to tell how the page was unloaded or otherwise get more details about what the user is doing to unload the page. (jquery solutions welcome).
Code for reference:
window.onbeforeunload = function () {
if (formIsDirty) {
formIsDirty = false;
return "Are you sure you want to navigate away from this page?";
}
}
on beforeunload event we can do below things:
We can pass event as a parameter to the function as in above answer.
Now we can use this event for available information attached to this
event.
And we can access Document level variables.
For example document.activeElement will give you the last element you clicked that caused the page unload.
Hope this helps!!
I think that the active element is not a valid solution.
I can't comment the "open and free" solution, I dont have reputation.
document.getActiveElement gets the currently focused element in the document. If a link have the focus and I press F5 or I close the tab the active element is the link.
Short answer: There's no easy way to find out what is causing onbeforeunload to fire.
Long answer: Inside your window.onbeforeunload handler you can access the window.event object, which may have some useful properties to determine how the window is closing.
For example, if window.event.srcElement is an anchor tag, then you know that the onbeforeunload event is firing by an anchor tag being clicked.
Refer to the event and onbeforeunload pages on MSDN for more properties.
Edit: some more info I have stumbled across -
If you want to ignore ASP controls that cause post-back, you can interrogate the '__EVENTTARGET' hidden input. If this input has a non-empty string value, then the page is being posted back by an ASP control.
You could also check the keyCode property (if F5 has been pressed, causing a refresh) or the mouse position to see if the X (close) button has been clicked.
I was running into a simular issue when a user was hitting enter from an input field on a form. The form was being submitted thus firing off the onbeforeunload event. I tried setting a flag to avoid showing the message on the keydown event on the input, filtering on the enterkey code. This wasn't getting triggered until after the onbeforeunload event was firing and therefore the flag wasn't getting set.
I then looked into the _EVENTTARGET as jbabey suggested. If the form was being submitted there would be a value in that field, if it was being refreshed there wouldn't.
Therefore, doing a simple check to see if there was value in the _EVENTARGET field in the onbeforeunload event could determine if the input from the form was causing the postback.
Here is my code.
window.onbeforeunload = function (e) {
if ($('[id$=__EVENTTARGET]').val().indexOf('btnValidateMaterials') != -1) {
confirmExit = false;
}
if (DateOrQtyHasChanged() && confirmExit) {
if (/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
var message = $('[id$=hfLeaveMessageFF]').val();
if (confirm(message)) {
history.go();
}
else {
window.setTimeout(function () {
window.stop();
}, 1);
}
}
else {
var message = $('[id$=hfLeaveMessage]').val();
return message;
}
}
}

window.onbeforeunload handling ok and cancel options

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
}

Categories

Resources