How to remove prompt on unload event using javascript - 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);
}

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

Event to be triggered when leaving website or closes the browser

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

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

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

Categories

Resources