IE9 confirm browser exit - javascript

There is a lot of questions on stackoverflow.com about this issue. But there is really no answer, or I couldn't find it (in that case, I am sorry for this duplicate).
So I have an Ajax based web application, and I want to know if user want's to leave the page. Here's a snippet what I have:
function goodbye(e) {
if(!stopGoodbye) {
if(!e) e = window.event;
e.cancelBubble = true;
e.returnValue = 'You are leaving the system!';
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
}
window.onbeforeunload=goodbye
stopgoodbye is for turning off when clicking logout.
This works in Firefox, but in IE9 it is showing the dialog everytime user clicks a link which just changes some DIV content (an Ajax link)... If it helps, I am using Struts2 framework with jQuery.

you can actually turn the onbeforeupload warning off for the user(when they clicked on a link) by adding an onclick event to the anchor.
you can read more about here, the solution are in the comments

Related

Restrict user from closing tabs or window of browser

How do I restrict my user from closing the tabs or browser while accessing any specific page.
window.onbeforeunload = function(e) {
if (!e) e = window.event;
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?';
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
return 'You sure you want to leave?';
return false;
}
I tried above code but it gives popup for leave the page or stay on the page on chrome browser.
You can't.
The browser is software that belongs to the user. It is completely under their control. If they want to quit, they can quit.
You need to design your system so it is robust enough to handle people quitting part way through.

Prevent double submission with prevent window event issue

I'm using the following function to prevent double submissions:
$("#form").submit(function () {
var form = $(this);
form.find("input[type=submit]").attr("disabled", "disabled")
form.find("input[type=submit]").attr("value", "Processing");
});
It works fine, but then I have the following code which triggers an alert to avoid accidentally leaving the page:
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = '¿DO YOU REALLY WANT TO LEAVE THIS PAGE?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
The problem is if the user clicks submit and the realizes he didnt want to leave the page and clicks on stay on this page instead, the submit button is still disabled.
How could I re-enable it upon clicking stay on this page?
Thanks!
The button problem
You want to disable and enable the submit button so you know you going to touch the same kind of function and object twice, it is better to make advantage out of this in a function
function disableSubmit(form, enabled){
var submit = form.find("input[type=submit]"),
dataVar = enabled !== true ? "processing-message" : "send-message",
message = submit.data(dataVar);
submit.prop('disabled', (enabled !== true) );
submit.val(message);
}
I could make it even more generic for using it on each form. But the message in the button will display whatever you put in the data-attribute.
Cancel Submit
There is a problem with cancellation of an onbeforeunload event; there is no callback for it. The solution I came with is using a timeout. Since you don't know if the person canceled or not, I think 2 seconds is enough for the page to submit.
You have to have 2 seconds patient to get the submit button enabled again. But you can adjust it all you want of course
if (e.stopPropagation) {
setTimeout(function () {
disableSubmit(formObject, true);
}, 2000);
e.stopPropagation();
e.preventDefault();
}
The JSFiddle example

JavaScript confirm to fire when user clicks to close their browser (but not when they click the refresh button)

There are several similar questions on here already but none of them provide a solution to what I'm looking for here.
When a user clicks the close button on their browser I need to pop up an alert to confirm that they really want to close their browser. This is easy enough to write:
$(window).bind('beforeunload', function(){
return 'Are you sure you want to close your browser?';
});
The problem with this is that it also fires when you do things like refresh your browser, click on buttons and links, etc.
Most of these can be prevented by detecting the key presses and checking the keyCodes like this:
if (e.keyCode == 114 || e.keyCode == 116 || e.keyCode == 0 || e.keyCode == 17 ||(e.ctrlKey && e.keyCode == 114)){
confirmBrowserClose = false;
}
$("a").bind("click", function() {
confirmBrowserClose = false;
});
$("form").bind("submit", function() {
confirmBrowserClose = false;
});
$("input[type=submit]").bind("click", function() {
confirmBrowserClose = false;
});
These things prevent most of them but one thing it doesn't work for is refresh. I can prevent it from firing when the user refreshes using the keyboard (like F5) but I need to know how to prevent my confirmation alert from firing when the user clicks the refresh button or enter in the URL window.
Most of what I've found scattered around the internet says that it either can't be done or they talk about things like using the keyCodes and F5 refresh. I know this can be done because there are many sites that have this functionality working. A couple sites that are using it are Facebook and JSFiddle.net. In Facebook, if you start typing a status update and then try to close your browser, it will popup a confirmation. In JSFiddle, if you make changes to your fiddle and then try to close your browser it will pop up a warning alert that your changes will be lost if you close.
Does anyone know how to do this?
This is not possible. If you observe properly, even Facebook.com and JSFiddle.net do not have this feature.
beforeunload is the only event that gets triggered on leaving the page.(either by page refresh [f5, ctrl+r], tab close, load another link[this also accounts to leaving the current page, hence triggering beforeunload])

Capturing result of window.onbeforeunload confirmation dialog

Is there a way to capture to result of the window.onbeforeunload confirmation dialog like the one below from Stack Overflow (this happens when leaving the 'Ask Question' page without posting the question)?
This is how it appears in Chrome, I believe it's slightly different in other browsers, but you always have some form of yes/no buttons.
Presumably if they're still on the offending page after the event has been triggered they chose to stay and you could probably figure this out by watching the sequence of js. However I would like to know how to determine if they clicked "Leave this page"?
I've implemented this like below:
// concept taken from SO implementation
function setConfirmUnload(showMessage, message) {
window.onbeforeunload = showMessage ? (message ? message : "this is a default message") : null;
}
// pseudo code
listen to changes on inputs
if any inputs fire a change event
call setConfirmUnload(true, 'My warning message')
note I'm using jQuery within my site.
I'm essentially trying to implement a Gmail like drafting implementation, wherein if a user leaves a page with a form they've made changes to without saving they're warmed with a similar dialog. If they choose to discard they're changes and leave the page, I need to clean up some temporary records from the database (I'm thinking an AJAX call, or simply submitting the form with a delete flag) then sending them on their way.
My question also relates to:
jQuery AJAX call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?
You can have the exit confirmation using window.onbeforeunload but there isn't a way to find out which button the user clicked on.
To quote an earlier response from jvenema from this thread:
The primary purpose for the
beforeunload is for things like
allowing the users the option to save
changes before their changes are lost.
Besides, if your users are leaving,
it's already too late [...]
How about this:
$( window ).bind( 'beforeunload' , function( event ) {
setTimeout( function() {
alert( 'Hi againe!' );
} );
return '';
} ).bind( 'unload', function( event ) {
alert( 'Goodby!' );
} );
Late to the party, but I found the following code (in TypeScript) to be a decent way to detect if the person clicked on 'Ok' on that confirmation dialogue window.
public listenToUnloadEvents(): void {
window.addEventListener('beforeunload', (e) => {
const confirmationMessage = '\o/';
(e || window.event).returnValue = confirmationMessage; // Gecko + IE
return confirmationMessage; // Webkit, Safari, Chrome etc.
});
window.addEventListener('unload', () => {
this.sendNotification(Action.LEFT)
});
}
I'm not sure how much time you have to run code in the unload event, but in this instance, I am sending a notification through Socket.io, so it's very quick at completing.
As for detecting the cancel on that notification, as someone else mentioned, creating a global variable like let didEnterBeforeUnload = false could be set to true when the beforeunload event fires. After this, by creating the third event, like so (again, in TypeScript), you can infer the user pressing cancel
window.addEventListener('focus', (e) => {
if (didEnterBeforeUnload) {
console.log('pressed cancel')
}
didEnterBeforeUnload = false
});
As a side-note though, these events won't (iirc) fire unless you have interacted with the page. So make sure to click or tap into the page before trying to navigate away during your testing.
I hope this helps anyone else out there!

Stop User Leaving Before Postback (Javascript/ASP.NET)

I have several functions running on a postback that can take a little time to complete.
When postback is initiated I show a loading image with this code:
function showLoader()
{
document.getElementById("<%=loadingImage.ClientID%>").style.visibility="visible";
}
I want to be able to add code to this function so if user tries to leave at this point they are informed the operation is not complete.
I found this code:
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
This works but I only want the code to be active when the loading image is active.
I tried the following but it shows the alert message when the page eventually posts back:
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
function showLoader()
{
document.getElementById("<%=loadingImage.ClientID%>").style.visibility="visible";
window.onbeforeunload=goodbye;
}
Any ideas how I can tweak this to just show when user leaves page and not when postback completes?
You need to set window.onbeforeunload to null when a form get submitted. So, basically:
<form onsubmit="window.onbeforeunload=null">
To apply this on all forms dynamically, I'd suggest to write a window.onload function for this which does this without the need to edit every single form on all your pages.

Categories

Resources