The best way to implement window close event - javascript

Long story is short - I am trying to submit a certain form when user closes the window, or is not responding for 20min.
The second I've done using this code:
timeOut = setTimeout(function () {
submitThisForm(document.forms.sendDealerInfo);
console.log("Timed out...");
}, 600000);
For the first one I've tried with this code:
window.onbeforeunload = function() {
submitThisForm(document.forms.sendDealerInfo);
clearTimeout(timeOut);
return null;
}
Unfortunately window.onbeforeunload event won't trigger in all browsers (in Chrome and Opera for example).
I also tried: $(window).unload(function () {... and window.addEventListener("beforeunload", function (event) {...
But same story - they won't work in all browsers.
Is there a way to accomplish what I am trying to do some other way? Perhaps with sessions?

As Suman says, onBeforeUnload is supported in all the major browsers. But most, if not all, the browsers will not let you do anything within that event beyond returning a string for the "Are you sure you want to leave this page?" dialog.
Then with onUnload you're attempting to submit a form after the page has already been unloaded, and navigation is already happening. It would be a very odd user experience to be navigating away then be redirected somewhere else.
Trying to submit a form when the window is closed isn't a very safe method. The web browser could crash, the user could force close it, the internet connection could be interrupted, among other things. I think your best bet would be to submit the form every so often. Possibly detecting an idle timeout of a few seconds, then submitting your form?

window.onbeforeunload is works in all major browsers, Like it is supported from Chrome 1 and Opera 12
Browser Compability

Related

Is there any way to handle the browser/tab close other than beforeunload or onbeforeunload or unload

Is there any way to handle the browser/tab close other than beforeunload or onbeforeunload or unload. because I tried all the 3 events but the default pop up is coming. I don't want that default pop up but I want do something on the close click.
You can't outright block the closure of a window/tab with preventDefault or any other method. Because of this limitation, you can't use a custom modal, etc. to show a message. Your only option is to return a message, which can be bypassed.
window.onbeforeunload = function(){
return "Do you want to leave?";
}
(Demo: http://jsfiddle.net/9sAE4/embedded/result/)
Note that Firefox does not presently show the user the included message, but rather a generic message asking if the user wishes to leave.
No. The only way to do anything when the window is closed is to use onbeforeunload, and the things you're allowed to do are quite limited. Firefox and Chrome prevent your using alert or confirm, for instance (but do support returning a string from the handler, which then they'll use to show the user the choice to stay on the page). Some browsers may allow synchronous ajax calls, but I don't think all do, and I'd avoid it if I were you. You can probably set items in local storage.
From your comment:
I dont want to close the browser/tab and I want to show my own Pop up
You can't. All you can do is hook onbeforeunload and return a string, which the browser will use to offer the user a chance to stay on the page. You can't style that window, or control it.
window.onbeforeunload = function() {
return "Your message here.";
};
Example
Note that recent versions of Firefox don't even show your message, they just use a generic "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (or similar) instead.

How to disable the back button in the iPad's browser

Below is my code to detect and stop the browser's back button in iPad browsers.
$(window).bind("pagehide", function(e) {
})
How can I stop the page going back on browsers' back button click in iPad browsers?
You can use the onbeforeunload event that triggers when a user is leaving your page, whether it's by hitting the back button, entering a new URL or closing the browser.
Here is an example:
window.onbeforeunload = function(){
return 'You are leaving!?';
}
And here is the result on Chrome:
This event seems to be inconsistent across browsers as some will not support it, some will execute whatever function you pass it, and some will reject the function if it doesn't return a string to put in the confirmation box.
As commenter Alex Wayne stated, think twice about this. It can really create a negative impact on your site or webapp to alter the native behaviour of the back button.

Preventing web browser from closing until AJAX response is returned [duplicate]

This question already has answers here:
JavaScript, browsers, window close - send an AJAX request or run a script on window closing
(9 answers)
Closed 6 years ago.
I've got a game that runs in the web browser (as a plugin) and what I'm trying to do is:
Detect if the user has decided to close the browser (Alt+F4, hitting the 'X' button etc)
Prevent the browser from closing whilst we fire a call to our web services to log that the user has closed the browser
Once we receive the response from the web services, release the lock and allow the browser to close as requested.
The main reason we want to do this is we're having some concurrency problems and going through our logs we want to isolate people logging out / closing the browser from genuine instances where the plugin has crashed.
I looked into doing this with JQuery (for X-Browser compatability - Opera won't work but we don't have any users on Opera anyway thankfully):
$(window).bind('beforeunload', function(e) {
e.preventDefault();
// make AJAX call
});
The problem is that this displays a confirmation dialog to the user ('Are you sure you want to leave this page') which the user might confirm before the AJAX call is sent.
So the question is, is there a way of preventing the browser from closing until the response is received? Also 'beforeunload' fires when the page is changed as well - is there a way of distinguishing clicking on a link from actually clicking close?
Grateful for any help wrt to this!
Its tricky business to avoid the browser window from beeing closed. Actually, there is no way to do that, beside returning a non-undefined value from the onbeforeunload event, like you described.
There is one possible suggestion I can make, that is creating a synchronized ajax request within the onbeforeunload event. For instance
window.onbeforeunload = function() {
$.ajax({
url: '/foo',
type: 'GET',
async: false,
timeout: 4000
});
};
In theory, this will block the browser for a maximum of 4 seconds. In reality, browsers will treat this differently. For instance, Firefox (I tested it on 9), will indeed not close the window immediately, but it also does not respect the timeout value there. I guess there is an internal maximum of like 2 seconds before the request is canceled and the window/tab gets closed. However, that should be enough in most cases I guess.
Your other question (how to distinguish between clicking a link), is fairly simple. As described above, onbeforeunload looks what is getting returned from its event handlers. So lets assume we have a variable which is global for our application, we could do something like
var globalIndicator = true;
// ... lots of code
window.onbeforeunload = function() {
return globalIndicator;
};
At this point, we would always receive a confirmation dialog when the window/tab is about to get closed. If we want to avoid that for any anchor-click, we could patch it like
$( 'a[href^=http]' ).on('click', function() {
globalIndicator = undefined;
});
As for the first part of your question, there is no reliable way of preventing the browser from closing other than using window.onbeforeunload. The browser is there to serve the user and if the user chooses to close his browser then it will do so.
For your second question, it is reasonably easy to distinguish a click on a link from other events triggering an onbeforeunload event by jQuery:
$('a').click(function(e) {...});
You could use this, for example, to make sure a click will not trigger unbeforeunload:
$('a').click(function(e) {window.onbeforeunload = null});
You can use below code to prevent the browser from getting closed:-
window.onbeforeunload = function() {
//Your code goes here.
return "";
}
Now when user closes the browser then he gets the confirmation dialogue because of return ""; & waits for user's confirmation & this waiting time makes the request to reach the server.
I'm pretty sure that what you want isn't possible using JavaScript. But since you have a browser plugin, shouldn't you be able to check whether your plugin object was cleaned up correctly? I'm not sure if you're using ActiveX, NPAPI or something like Firebreath, but these frameworks all have lifecycle methods that will be called on your plugin in the event of a normal shutdown, so you should be able to write something to the logs at this point. If the plugin crashes, these won't be called.

Find browser close/refresh using javascript/jquery

Could someone explain if there is a way to differentiate between browser close and refresh events using javascript/jquery.
Basically, I need to log-out the user if he is closes the tab.
I tried using jQuery .unload(). But that is firing for Refresh and Form Submit. I tried assigning a global variable and avoided .unload() during Form Submit. But how this can be avoided for Refresh, or if there is any other work-around to achieve this..
I wonder if the same can be done only if the window is closed(instead of tab).
You could try using an instance cookie, ie one that is delete once the browser is closed, you could then check for the cookies existence from JavaScript. otherwise I don't think there is a way to tell the difference your looking for with just javascript.
Unfortunately, JavaScript only provides onunload, which will fire whenever the user navigates away from, closes or reloads the current page.
Robert is correct, this is a good situation for session cookie: if you create a cookie without specifying an Expiration, it will expire when the tab/window is closed by the user.
You might not be able to do that other than some cookie based methods like non persistent cookies which is a work around. Second, it is not that easy to differentiate a page refresh, form based page redirect unload, or browser close. Its difficult to identify as far as I know.
you can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
/* Do you small action code here */
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload
Sadly, the implementation of onunload or onbeforeunload isn't that great between browsers and in cases of a crash the unload event will never be fired. You're best bet is to not worry about catching the unload events and just have sensible session expiration times.
If you didn't have to worry about distinguish between form submits and refreshes you could could get pretty good coverage with onunload, but it still wouldn't be 100%.

Prevent browser from closing in asp.net

I am using asp.net 2.0 with c#.
i want a pop up to be displayed when user tries to close the browser and if user click on "no" [i.e. he don't want browser to be closed] then it prevent browser to get closed.
Please help.
Thanks
the code they use is
window.onbeforeunload=function() {
if (somereasonorother) return "You did not save your stuff"
}
Pointy, this is entirely possible, and it's done by many web pages for perfectly reasonable reasons.
Try something like this:
function areYouSure() {
return "Are you sure you want to leave this page?";
}
window.onbeforeunload = areYouSure;
You can try to attach yourself to the onbeforeunload event:
<body onbeforeunload="ConfirmClose();">
But I have to mention that it won't work on all browsers. The only ones that prompted something after I closed a window were Chrome, Firefox and Internet Explorer; Opera ignored the code in the JavaScript method.
This is mostly because some browsers trigger the onbeforeunload event only when you're trying to leave the current page by visiting another one, and not when you close the current window / tab.

Categories

Resources