Is there any cross-browser JavaScript/jQuery code to detect if the browser or a browser tab is being closed, but not due to a link being clicked?
-
1See my answer to this question: http://stackoverflow.com/questions/3735198/is-it-possible-to-add-a-browser-code-in-javascript/3735851#3735851 – Nivas Oct 08 '10 at 08:51
-
You can! http://stackoverflow.com/questions/42706209/net-core-cookies-authentication-on-browser-close/42706331#42706331 – AP. Mar 09 '17 at 22:19
-
Use `sessionStorage ` Property, it will expire once the browser closes. https://www.w3schools.com/jsref/prop_win_sessionstorage.asp – csandreas1 May 07 '18 at 07:52
-
Check this answer! I found it extremely useful and covers majority of the cases. https://stackoverflow.com/a/26275621/7192927 – Sukanya Pai Sep 06 '19 at 05:59
-
Does this answer your question? [How to capture the browser window close event?](https://stackoverflow.com/questions/1631959/how-to-capture-the-browser-window-close-event) – Syed M. Sannan Feb 28 '22 at 17:49
-
I also tried many ways, but finally SignalR helped me: https://stackoverflow.com/questions/76139970/trying-to-detect-browser-close-event-using-signalr – Behnam Faghih May 03 '23 at 07:06
25 Answers
If I get you correctly, you want to know when a tab/window is effectively closed. Well, AFAIK the only way in JavaScript to detect that is to use either onunload
or onbeforeunload
events.
Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close
in JavaScript. Correct me if I'm wrong here.

- 4,555
- 31
- 31
- 45

- 231,737
- 57
- 305
- 359
-
49Correct. You can only detect when the page is unloaded, not when the window is closed. Also, the onbeforeunload is non-standard, so it's not supported by all browsers. – Guffa Oct 08 '10 at 08:45
-
10I wanted to use the 'on close' feature as well, but noticed that my users will occasionally refresh the screen by pressing F5. Since my 'on close' handlers are invoked on such refresh, this means I can't use it the way I needed it (which was a true 'close tab or window')... damn it, we need a new event model for all of this! – Jeach Apr 25 '13 at 17:06
-
2No longer works on chrome/opera...https://www.chromestatus.com/feature/5349061406228480 – Samir Seetal Jun 15 '17 at 10:10
-
5Of course this will still work, they just removed a custom `String` return value from `onbeforeunload`. So now you're no longer be able to display a custom message before unloading. – jAndy Jun 16 '17 at 15:37
-
2
-
2@EgorDudyak The event is fired for the window. If you use the same method for multiple windows, you can use the `target` property of the event object. – Guffa Feb 27 '20 at 19:04
-
I just realized that makes it pretty much the same as visibilitychange – LuckyLuke Skywalker Apr 10 '23 at 21:17
From MDN Documentation
For some reasons, Webkit-based browsers don't follow the spec for the dialog box. An almost cross-working example would be close from the below example.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
This example for handling all browsers.

- 1
- 1

- 10,837
- 4
- 39
- 51
-
2This is the only solution that worked for my chrome browser. I didn't try any others. – Chase Roberts Jan 07 '14 at 00:10
-
4yee, i try a lot of solutions and i come with this at end, combination for best answers, and i tests it on all browsers. – mohamed-ibrahim Jan 08 '14 at 11:08
-
1This method is not working perfectly on tab close while using firefox (>= ver. 44) with only tab opened. – Raj May 24 '16 at 15:04
-
As of today, using all the latest versions of browsers, prompt works when closing tab, navigating away or closing browser for Chrome, Firefox, Opera, IE11 and Edge and also works when you have multiple tabs opened except for Chrome where Chrome closes all tabs without prompting, well on my machine at least. – Thierry Sep 27 '18 at 15:24
-
not giving a proper out out as defined in question. This also triggered on page leave event not only the browser close or tab close – Sunil Acharya Dec 25 '18 at 08:20
-
1It's not possible to provide a custom message to `beforeunload` or `onbeforeunload`. Here's the browser compatibility as in 2019: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Browser_compatibility – Kenny Alvizuris Jun 18 '19 at 09:13
-
-
Is this still up to date? it is not working for me on chrome 89.0.4389.72 nor firefox 88.0.1. I get the prompt if I reload on chrome but not when I close the tab or the window – raquelhortab May 19 '21 at 14:55
-
the prompt window appears but I cannot set it to wotk with custom message...it show the default – Dimitris Papageorgiou Mar 06 '22 at 09:24
Simple Solution
window.onbeforeunload = function () {
return "Do you really want to close?";
};
-
11What kind of sorcery is this? (y) does it works on all browsers? works great on chrome – Ziv Weissman Sep 14 '16 at 14:20
-
11
-
8
-
2This also triggered on page leave event not only the browser close or tab close – Sunil Acharya Dec 25 '18 at 08:20
<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">
var myclose = false;
function ConfirmClose()
{
if (event.clientY < 0)
{
event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
setTimeout('myclose=false',10);
myclose=true;
}
}
function HandleOnClose()
{
if (myclose==true)
{
//the url of your logout page which invalidate session on logout
location.replace('/contextpath/j_spring_security_logout') ;
}
}
//This is working in IE7, if you are closing tab or browser with only one tab

- 255
- 2
- 2
-
2ya. but for multiple tab browser like ie8, firefox. there is problem using this? – cometta Apr 09 '11 at 05:03
-
It turns out that using this code in IE9 will cause this message to pop up when the user clicks the back, forward, or refresh buttons with their mouse. – Steve Wortham Mar 13 '12 at 16:20
-
Just a heads up that we implemented a similar solution back in 2007. This solution no longer works in IE9 as of about a week ago. It stopped working (or possibly never worked) in tabbed browsers long ago. – tjfo Jul 17 '13 at 16:17
-
I injected `window.onunload = "alert('wait')"` and `window.onbeforeunload = "alert('wait... chrome!')"` using the console in Chromium/Ubuntu but neither fired when I closed the tab. – icedwater Apr 15 '14 at 03:34
-
`window.onunload = "alert('wait')"` and suchlike should not work really. "The function should assign a string value to the returnValue property of the Event object and return the same string". Please take a look at [MDN article](https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload) – Dmytro Vyprichenko May 21 '14 at 09:33
-
@jyothis does this still work in 2022? Looks ideal for what I am trying to do, but I have not found a way to get it to work – Sep 22 '22 at 12:48
For similar tasks, you can use sessionStorage
to store data locally until the browser tab is closed.
The sessionStorage
object stores data for only one session (the data is deleted when the browser tab is closed).(W3Schools)
<div id="Notice">
<span title="remove this until browser tab is closed"><u>dismiss</u>.</span>
</div>
<script>
$("#Notice").click(function() {
//set sessionStorage on click
sessionStorage.setItem("dismissNotice", "Hello");
$("#Notice").remove();
});
if (sessionStorage.getItem("dismissNotice"))
//When sessionStorage is set Do stuff...
$("#Notice").remove();
</script>

- 2,026
- 1
- 26
- 48
-
1Brilliant Idea. Used that for an online-timer that works consitent over multiple pages. I only was aware of localStorage so far. – André R. Kohl Sep 02 '20 at 13:39
I needed to automatically log the user out when the browser or tab closes, but not when the user navigates to other links. I also did not want a confirmation prompt shown when that happens. After struggling with this for a while, especially with IE and Edge, here's what I ended up doing (checked to work with IE 11, Edge, Chrome, and Firefox) after basing the approach on this answer.
First, start a countdown timer on the server in the beforeunload
event handler in JS. The ajax calls need to be synchronous for IE and Edge to work properly. You also need to use return;
to prevent the confirmation dialog from showing like this:
window.addEventListener("beforeunload", function (e) {
$.ajax({
type: "POST",
url: startTimerUrl,
async: false
});
return;
});
Starting the timer sets the cancelLogout
flag to false. If the user refreshes the page or navigates to another internal link, the cancelLogout
flag on the server is set to true. Once the timer event elapses, it checks the cancelLogout
flag to see if the logout event has been canceled. If the timer has been canceled, then it would stop the timer. If the browser or tab was closed, then the cancelLogout
flag would remain false and the event handler would log the user out.
Implementation note: I'm using ASP.NET MVC 5 and I'm canceling logout in an overridden Controller.OnActionExecuted()
method.

- 501
- 2
- 6
- 14

- 2,303
- 2
- 28
- 36
-
This worked great. Is there a reason you make "async: false"? This generates warnings that synchronous AJAX calls are deprecated. Thanks! – cat_in_hat Jul 16 '18 at 13:49
-
1@FoundWaldoException, as noted in the answer, I found that async needed to be set to false in order for this to work in IE and Edge. – Ionian316 Jul 23 '18 at 14:38
-
-
I found a way, that works on all of my browsers.
Tested on following versions: Firefox 57, Internet Explorer 11, Edge 41, one of the latested Chrome (it won't show my version)
Note: onbeforeunload fires if you leave the page in any way possible (refresh, close browser, redirect, link, submit..). If you only want it to happen on browser close, simply bind the event handlers.
$(document).ready(function(){
var validNavigation = false;
// Attach the event keypress to exclude the F5 refresh (includes normal refresh)
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
window.onbeforeunload = function() {
if (!validNavigation) {
// -------> code comes here
}
};
});

- 1,056
- 10
- 25
-
How a seperate handler for browser close will added..I dont think we have seperate event for this. – blazehub Aug 15 '18 at 03:37
-
1This was very helpful. I needed to adjust the A anchor to only fire for actual hyperlinks. Otherwise clicking on bootstrap tabs messed it up: $("a[href!='']").not('[href^="#"]').bind("click", function () – Ken Forslund Oct 11 '19 at 21:27
There is no event, but there is a property window.closed
which is supported in all major browsers as of the time of this writing. Thus if you really needed to know you could poll the window to check that property.
if(myWindow.closed){do things}
Note:
Polling anything is generally not the best solution. The window.onbeforeunload
event should be used if possible, the only caveat being that it also fires if you navigate away.

- 7,209
- 1
- 21
- 31
Sorry, I was not able to add a comment to one of the existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except for kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.
However, I do agree that the lack of a real close event is terrible: if you, for instance, want to reset your session state at the back-end only in case of the really close, it's a problem.

- 501
- 2
- 6
- 14

- 111
- 1
- 4
$(window).unload( function () { alert("Bye now!"); } );

- 10,154
- 16
- 53
- 72
-
10This won't work on Firefox or Chrome. Try `beforeunload` if want to display an alert. Like this: `$(window).on('beforeunload', function(){ alert ('Bye now')});` – AdrianoRR Mar 12 '13 at 21:51
-
7as per jQuery docs "Most browsers will ignore calls to alert(), confirm() and prompt()" https://api.jquery.com/unload/ – katzmopolitan Nov 23 '15 at 18:15
onunload is the answer for Chrome. According to caniuse its crossbrowser. But not all browsers react the same.
window.onunload = function(){
alert("The window is closing now!");
}
These events fire when the window is unloading its content and resources.
For Chrome:
onunload executes only on page close. It doesn't execute even on page refresh and on navigating to a different page.
For Firefox v86.0:
It wouldn't execute at all. Page refresh, navigating away, closing browser tab, closing browser, nothing.

- 424
- 3
- 10
Since no one has mentioned it yet (8+ years later): A WebSocket can be another effective way to detect a closed tab. As long as the tab is open and pointed at the host, the client is able to maintain an active WebSocket connection to the host.
Caveat: Please note that this solution is really only viable for a project if a WebSocket doesn't require any additional significant overhead from what you are already doing.
Within a sensible timeout period (e.g. 2 minutes), the server side can determine that the client has gone away after the WebSocket has disconnected and perform whatever action is desired such as removing uploaded temp files. (In my extremely specialized use-case, my goal was to terminate a localhost app server three seconds after the WebSocket connection drops and all CGI/FastCGI activity terminates - any other keep-alive connections don't affect me.)
I had problems getting the onunload event handler to work properly with beacons (as recommended by this answer). Closing the tab did not appear to trigger the beacon and open tabs triggered it in ways that could potentially cause problems. A WebSocket solved the problem I was running into more cleanly because the connection closes roughly around the same time that the tab closes and switching pages within the application simply opens a new WebSocket connection well within the delay window.

- 2,274
- 24
- 20
-
2that is okay. But, can not you share any code or procedure to handle it? Without that for a noob like me can not understand – Satish Patro Mar 01 '19 at 12:00
-
Actually, I was not clear in my first comment. I do not know web socket. So, I just wanted to see how to handle – Satish Patro Mar 04 '19 at 05:39
-
1The link in my comment above goes to some example WebSocket JS code. The client JS portion is the easy part. That code is for my very specific use-case though where I need to terminate the entire application server in a timely fashion. How you write a WebSocket server is up to you and requires server-side configuration to connect everything up (a lot people prefer a NodeJS backend w/ Nginx frontend). Writing a TCP/IP enabled server is a complex topic not suitable for discussion in comments and it's overkill to set one up just for detecting this particular issue. – CubicleSoft Mar 04 '19 at 07:12
It can be used to alert the user if some data is unsaved or something like that. This method works when the tab is closed or when the browser is closed, or webpage refresh.
It won't work unless the user has not interacted with the webpage, this is a mechanism to fight malicious websites..... there will be no popup unless you atleast make a click or touch on the website window.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<textarea placeholder = "Write...."></textarea>
</form>
<script type="text/javascript">
window.addEventListener('beforeunload', function (e) {
e.returnValue = '';
});
</script>
</body>
</html>

- 6,112
- 6
- 36
- 40

- 323
- 1
- 9
window.onbeforeunload = function() {
console.log('event');
return false; //here also can be string, that will be shown to the user
}

- 2,913
- 2
- 30
- 30
-
2`here also can be string, that will be shown to the user` it doesn't, on firefox, it does in chrome however... – TrySpace Feb 13 '14 at 14:38
-
Any return value (string) is displayed only in MSIE <= 11. So basically useless for all other browsers. – OSWorX Mar 17 '19 at 08:33
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "tab close";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
sendkeylog(confirmationMessage);
return confirmationMessage; //Webkit, Safari, Chrome etc.
});

- 132,869
- 46
- 340
- 423

- 309
- 3
- 2
-
Actually I wanted to show confirmation Message if user close the Tab then ONLY. This is working for me. But I am facing a issue that, If I am clicking on any link of same page then also its showing confirmation message.For moe refer : https://www.w3schools.com/code/tryit.asp?filename=FEK2KWUN9R8Z @Tunaki – Mohammed Apr 12 '17 at 09:50
-
2
//Detect Browser or Tab Close Events
$(window).on('beforeunload',function(e) {
e = e || window.event;
var localStorageTime = localStorage.getItem('storagetime')
if(localStorageTime!=null && localStorageTime!=undefined){
var currentTime = new Date().getTime(),
timeDifference = currentTime - localStorageTime;
if(timeDifference<25){//Browser Closed
localStorage.removeItem('storagetime');
}else{//Browser Tab Closed
localStorage.setItem('storagetime',new Date().getTime());
}
}else{
localStorage.setItem('storagetime',new Date().getTime());
}
});
Hi all, I was able to achieve 'Detect Browser and Tab Close Event' clicks by using browser local storage and timestamp. Hope all of you will get solved your problems by using this solution.
After my initial research i found that when we close a browser, the browser will close all the tabs one by one to completely close the browser. Hence, i observed that there will be very little time delay between closing the tabs. So I taken this time delay as my main validation point and able to achieve the browser and tab close event detection.
I tested it on Chrome Browser Version 76.0.3809.132 and found working
:) Vote Up if you found my answer helpful....

- 61
- 1
- 5
-
Well, this gave me an idea. I am setting a timestamp plus 10 seconds in localstorage after login and on event beforeunload. On load I verify if time passed, then redirect to login page. Thanks :) – G4BB3R Feb 20 '20 at 18:33
-
I hate using code I don't understand. I understand what this is doing and it's definitely a hack - I just can't believe it's 2021 and there's not a better solution out there. – Travis L. Riffle Sep 09 '21 at 20:54
I have tried all above solutions, none of them really worked for me, specially because there are some Telerik components in my project which have 'Close' button for popup windows, and it calls 'beforeunload' event. Also, button selector does not work properly when you have Telerik grid in your page (I mean buttons inside the grid) So, I couldn't use any of above suggestions. Finally this is the solution worked for me. I have added an onUnload event on the body tag of _Layout.cshtml. Something like this:
<body onUnload="LogOff()">
and then add the LogOff function to redirect to Account/LogOff which is a built-in method in Asp.Net MVC. Now, when I close the browser or tab, it redirect to LogOff method and user have to login when returns. I have tested it in both Chrome & Firefox. And it works!
function LogOff() {
$.ajax({
url: "/Account/LogOff",
success: function (result) {
}
});
}

- 857
- 3
- 15
- 38
There have been updates to the browser to better tack the user when leaving the app. The event 'visibilitychange' lets you tack when a page is being hidden from another tab or being closed. You can track the document visibility state. The property document.visibilityState will return the current state. You will need to track the sign in and out but its closer to the goal.
This is supported by more newer browser but safari (as we know) never conforms to standards. You can use 'pageshow' and 'pagehide' to work in safari.
You can even use new API's like sendBeacon to send a one way request to the server when the tab is being closed and shouldn't expect a response.
I build a quick port of a class I use to track this. I had to remove some calls in the framework so it might be buggy however this should get you started.
export class UserLoginStatus
{
/**
* This will add the events and sign the user in.
*/
constructor()
{
this.addEvents();
this.signIn();
}
/**
* This will check if the browser is safari.
*
* @returns {bool}
*/
isSafari()
{
if(navigator && /Safari/.test(navigator.userAgent) && /Chrome/.test(navigator.userAgent))
{
return (/Google Inc/.test(navigator.vendor) === false);
}
return false;
}
/**
* This will setup the events array by browser.
*
* @returns {array}
*/
setupEvents()
{
let events = [
['visibilitychange', document, () =>
{
if (document.visibilityState === 'visible')
{
this.signIn();
return;
}
this.signOut();
}]
];
// we need to setup events for safari
if(this.isSafari())
{
events.push(['pageshow', window, (e) =>
{
if(e.persisted === false)
{
this.signIn();
}
}]);
events.push(['pagehide', window, (e) =>
{
if(e.persisted === false)
{
this.signOut();
}
}]);
}
return events;
}
/**
* This will add the events.
*/
addEvents()
{
let events = this.setupEvents();
if(!events || events.length < 1)
{
return;
}
for(var i = 0, length = events.length; i < length; i++)
{
var event = events[i];
if(!event)
{
continue;
}
event[1].addEventListener(event[0], event[3]);
}
}
/**
*
* @param {string} url
* @param {string} params
*/
async fetch(url, params)
{
await fetch(url,
{
method: 'POST',
body: JSON.stringify(params)
});
}
/**
* This will sign in the user.
*/
signIn()
{
// user is the app
const url = '/auth/login';
let params = 'userId=' + data.userId;
this.fetch(url, params);
}
/**
* This will sign out the user.
*/
signOut()
{
// user is leaving the app
const url = '/auth/logout';
let params = 'userId=' + data.userId;
if(!('sendBeacon' in window.navigator))
{
// normal ajax request here
this.fetch(url, params);
return;
}
// use a beacon for a more modern request the does not return a response
navigator.sendBeacon(url, new URLSearchParams(params));
}
}

- 434
- 5
- 15
window.onbeforeunload = function ()
{
if (isProcess > 0)
{
return true;
}
else
{
//do something
}
};
This function show a confirmation dialog box if you close window or refresh page during any process in browser.This function work in all browsers.You have to set isProcess var in your ajax process.
It is possible to check it with the help of window.closed in an event handler on 'unload' event like this, but timeout usage is required (so result cannot be guaranteed if smth delay or prevent window from closure):
Example of JSFiddle (Tested on lates Safari, FF, Chrome, Edge and IE11 )
var win = window.open('', '', 'width=200,height=50,left=200,top=50');
win.document.write(`<html>
<head><title>CHILD WINDOW/TAB</title></head>
<body><h2>CHILD WINDOW/TAB</h2></body>
</html>`);
win.addEventListener('load',() => {
document.querySelector('.status').innerHTML += '<p>Child was loaded!</p>';
});
win.addEventListener('unload',() => {
document.querySelector('.status').innerHTML += '<p>Child was unloaded!</p>';
setTimeout(()=>{
document.querySelector('.status').innerHTML += getChildWindowStatus();
},1000);
});
win.document.close()
document.querySelector('.check-child-window').onclick = ()=> {
alert(getChildWindowStatus());
}
function getChildWindowStatus() {
if (win.closed) {
return 'Child window has been closed!';
} else {
return 'Child window has not been closed!';
}
}

- 184
- 1
- 7
My approach would be along these lines:
- Listen for changes in the url with onpopstate and set a sessionStorage variable with 1
- Listen for page load and set that sessionStorage variable to 0
- On beforeunload, check if the variable is 0. If so it means that the user is closing and not changing url.
This is still a roundabout way to go, but makes sense to me

- 15
- 5
From an MDN page:
Avoid unload and beforeunload
In the past, many websites have used the
unload
orbeforeunload
events to send analytics at the end of a session. However, this is extremely unreliable. In many situations, especially on mobile, the browser will not fire theunload
,beforeunload
, orpagehide
events. For example, these events will not fire in the following situation:
- The user loads the page and interacts with it.
- When they are finished, they switch to a different app, instead of closing the tab.
- Later, they close the browser app using the phone's app manager.
The most reliable way to do this is to send the data on the
visibilitychange
event.
From visibilitychange
Usage notes:
This event fires with a
visibilityState
ofhidden
when a user navigates to a new page, switches tabs, closes the tab, minimizes or closes the browser, or, on mobile, switches from the browser to a different app. Transitioning tohidden
is the last event that's reliably observable by the page, so developers should treat it as the likely end of the user's session (for example, for sending analytics data).
In that first MDN page, it's also mentioned that we can use fetch()
with the keepalive
option set to true to send analytics data.
The
keepalive
option can be used to allow the request to outlive the page. Fetch with thekeepalive
flag is a replacement for theNavigator.sendBeacon()
API.

- 998
- 11
- 26
As @jAndy mentioned, there is no properly javascript code to detect a window being closed. I started from what @Syno had proposed.
I had pass though a situation like that and provided you follow these steps, you'll be able to detect it.
I tested it on Chrome 67+ and Firefox 61+.
var wrapper = function () { //ignore this
var closing_window = false;
$(window).on('focus', function () {
closing_window = false;
//if the user interacts with the window, then the window is not being
//closed
});
$(window).on('blur', function () {
closing_window = true;
if (!document.hidden) { //when the window is being minimized
closing_window = false;
}
$(window).on('resize', function (e) { //when the window is being maximized
closing_window = false;
});
$(window).off('resize'); //avoid multiple listening
});
$('html').on('mouseleave', function () {
closing_window = true;
//if the user is leaving html, we have more reasons to believe that he's
//leaving or thinking about closing the window
});
$('html').on('mouseenter', function () {
closing_window = false;
//if the user's mouse its on the page, it means you don't need to logout
//them, didn't it?
});
$(document).on('keydown', function (e) {
if (e.keyCode == 91 || e.keyCode == 18) {
closing_window = false; //shortcuts for ALT+TAB and Window key
}
if (e.keyCode == 116 || (e.ctrlKey && e.keyCode == 82)) {
closing_window = false; //shortcuts for F5 and CTRL+F5 and CTRL+R
}
});
// Prevent logout when clicking in a hiperlink
$(document).on("click", "a", function () {
closing_window = false;
});
// Prevent logout when clicking in a button (if these buttons rediret to some page)
$(document).on("click", "button", function () {
closing_window = false;
});
// Prevent logout when submiting
$(document).on("submit", "form", function () {
closing_window = false;
});
// Prevent logout when submiting
$(document).on("click", "input[type=submit]", function () {
closing_window = false;
});
var toDoWhenClosing = function() {
//write a code here likes a user logout, example:
//$.ajax({
// url: '/MyController/MyLogOutAction',
// async: false,
// data: {
// },
// error: function () {
// },
// success: function (data) {
// },
//});
};
window.onbeforeunload = function () {
if (closing_window) {
toDoWhenClosing();
}
};
};

- 1
- 1
-
1You have some issues in your javascript code. The first thing I noticed is that you will continually bind to `resize` when the window is blurred. If it gets blurred 100x then you'll have 100 listeners, which will end up slowing down the browser. – Kyle Jul 27 '18 at 20:59
-
-
Technically, but it’ll also remove any other handlers that were added elsewhere via jQuery. – Kyle Jul 28 '18 at 00:51
try this, I am sure this will work for you.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript'>
$(function() {
try{
opera.setOverrideHistoryNavigationMode('compatible');
history.navigationMode = 'compatible';
}catch(e){}
function ReturnMessage()
{
return "wait";
}
function UnBindWindow()
{
$(window).unbind('beforeunload', ReturnMessage);
}
$(window).bind('beforeunload',ReturnMessage );
});
</script>

- 11,391
- 14
- 81
- 114

- 41
- 2
- 11
Try this. It will work. jquery unload method is depreceted.
window.onbeforeunload = function(event) {
event.returnValue = "Write something clever here..";
};

- 504
- 5
- 7