Rectangle 27 30

the mouse will be out of the window, pointing out at the close button ('X')

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
    return "";
}
var prevKey="";
$(document).keydown(function (e) {            
    if (e.key=="F5") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
        window.onbeforeunload = ConfirmLeave;   
    }
    else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
        window.onbeforeunload = ConfirmLeave;
    }
    prevKey = e.key.toUpperCase();
});

The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().

what about firing up ajax when user press leave page button is it possible ?? if not than what can be the alternative of it

My favorite answer. This avoids listing all possible DOM elements that could lead you out of the page. And besides that the code also detects tab\window closing keyoard shortcuts.

Cannot read property 'toUpperCase' of undefined

Hi Shiv. This seems to be working fine for most cases except for ALT+F4 when there is no other tab i.e. open the page in browser and press Alt + F4. This closes browser without message. Ctrl + F4 works in the same situation.. Any Idea?

Also, it is firing in case you click browser back or forward as mouse is out of window for that buttons . :-(

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 51

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

$(function () {
    $("a").not('#lnkLogOut').click(function () {
        window.onbeforeunload = null;
    });
    $(".btn").click(function () {
        window.onbeforeunload = null;
});
});

The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.

One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.

did you see any errors in console?

@Ravi Code is fine. But I want to fire logout function if user click on "Leave this page". But how can I detect whether user has clicked "Leave this page" or not?

I'm not sure whether it is possible or not. As of I know it is not possible. However, can you post a new question with the reference to this answer, so that what community will say.

@Bit_hunter, you could execute a function where you show a custom div where the user can press Yes or No

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 168

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 kind of stuffs are onunload & 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.

Correct. 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.

I 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!

This works for me. However, my issue is a little more complicated. I'm trying to pass parameters into a method I assign to onbeforeunload from the codebehind. Could someone stop by stackoverflow.com/questions/28305430/ and weigh in?

Of 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.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 164

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 kind of stuffs are onunload & 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.

Correct. 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.

I 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!

This works for me. However, my issue is a little more complicated. I'm trying to pass parameters into a method I assign to onbeforeunload from the codebehind. Could someone stop by stackoverflow.com/questions/28305430/ and weigh in?

Of 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.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 10

Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return confirm("Do you really want to close?"); 
    });
});
  • enter something into html, css or javascript box
  • try to close tab in chrome

Doesnt work in Firefox v33

Sorry, In ubuntu I do not have Mozilla 33. So you can look up jsfiddle's implementation

Fiddle url is not working anymore.please check and update

@ShashankVivek fiddle link does working. Read answer once more. They removed "beforeunload" event handling from current version of web ui. So you will not see notification window anymore in jsfiddle. However using script upper you can still handle event by yourself. Nothing i can do.

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 3

As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return "Do you really want to close?"; 
    });
});

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 3

<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here 

    return "Please click 'Stay on this Page' and we will give you candy";
};
</script>

Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.

Response to question in comment

I would like detect only when the user closes tab or navigator and Alt+F4.

@Kiquenet I just tested Alt + f4 on IE8 and it did trigger mechanism, I must have done something wrong when testing Crome it triggers on all browsers (IE, Chrome, Firefox)

what about firing up ajax when user press leave page button is it possible ?? if not than what can be the alternative of it

Is there a way to avoid the message when the page is refreshed?

I was looking to detect the close event for an HTA app, this solution worked perfectly.

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 2

Hi i got a tricky solution, which works only on new browsers:

just open a websocket to your server, when the user closes the window, the onclose event will be fired

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 1

Use Session Storage in the browser. Here you don't want to capture the browser tab closing event. The Session Storage data persist for a session of opened tab

if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";

I grab those example code from Here

localStorage.removeItem(key);

I want to clear data on browser window close not on tab close. So, If i use sessionStorage then it'll clear on tab close also which i don't want to do.

but in your question you mention "whether browser tab is closed or browser window" therefore I post that answer. I will edit my answer. please wait

sorry for misrepresentation. I just wanted to detect if it is a browser tab or browser window closed by user. if it is browser window then clear localstorage else retain it. So i am not founding the way for that decision point tab or window. Thanks

reactjs - How to detect whether browser tab closed or browser window i...

javascript reactjs
Rectangle 27 13

You cannot detect when a user closes their browser or navigates off your site with PHP, and the JavaScript techniques of doing so are so far from guaranteed as to be useless.

  • Create a column in your user table along the lines of 'last_activity'.
  • Whenever a user loads a page, update their last_activity to the current time.
  • To get a list of who's online, just query the database for users with last_activity values more recent than 10/20/whatever minutes ago.

i used the method you described for a project once, and it works great. you can even use the mysql date and time functions, like timediff() and (time_to_sec(timediff(now(), last_activity))) to show the period (last activity: 15 minutes ago).

This looks like, it will make the database very busy if every page visited need to update database. is there any light way like Gumbo suggested? I am not very get his comment, not very understand...

If your site is so busy that an extra query per page bogs down your system, a "who's online?" page will be so huge as to be useless anyways. Gumbo's session method won't work for a "who's online?" page.

@show_lol, To prevent the potential load on the db you can keep track of the last time you updated your database. For instance, if it has been less than one minute since the last db update, it might not be necessary to update it again.

mysql - How to detect if a user has logged out, in php? - Stack Overfl...

php mysql session redirect logout
Rectangle 27 13

You cannot detect when a user closes their browser or navigates off your site with PHP, and the JavaScript techniques of doing so are so far from guaranteed as to be useless.

  • Create a column in your user table along the lines of 'last_activity'.
  • Whenever a user loads a page, update their last_activity to the current time.
  • To get a list of who's online, just query the database for users with last_activity values more recent than 10/20/whatever minutes ago.

i used the method you described for a project once, and it works great. you can even use the mysql date and time functions, like timediff() and (time_to_sec(timediff(now(), last_activity))) to show the period (last activity: 15 minutes ago).

This looks like, it will make the database very busy if every page visited need to update database. is there any light way like Gumbo suggested? I am not very get his comment, not very understand...

If your site is so busy that an extra query per page bogs down your system, a "who's online?" page will be so huge as to be useless anyways. Gumbo's session method won't work for a "who's online?" page.

@show_lol, To prevent the potential load on the db you can keep track of the last time you updated your database. For instance, if it has been less than one minute since the last db update, it might not be necessary to update it again.

mysql - How to detect if a user has logged out, in php? - Stack Overfl...

php mysql session redirect logout
Rectangle 27 3

There is no specific event for capturing browser close event. But we can detect by the browser positions XY.

<script type="text/javascript">
$(document).ready(function() {
  $(document).mousemove(function(e) {
    if(e.pageY <= 5)
    {
        //this condition would occur when the user brings their cursor on address bar 
        //do something here 
    }
  });
});
</script>

Hi there! I edited your post to put all the HTML in code format as it was incorrectly being parsed as HTML tags and not being displayed. In future, pay attention to the preview that shows what your post will look like, as your answer might look significantly different to what you expect!

javascript - Detect Close windows event by Jquery - Stack Overflow

javascript jquery javascript-events
Rectangle 27 5

Sorry, I was not able to add a comment to one of 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 of 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 the real close event is terrible: if you, for instance, want to reset your session state at the back-end only on case of the real close, it's a problem.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 5

Sorry, I was not able to add a comment to one of 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 of 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 the real close event is terrible: if you, for instance, want to reset your session state at the back-end only on case of the real close, it's a problem.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 1

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.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 1

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.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 2

$(window).unload( function () { alert("Bye now!"); } );
beforeunload
$(window).on('beforeunload', function(){ alert ('Bye now')});

as per jQuery docs "Most browsers will ignore calls to alert(), confirm() and prompt()" api.jquery.com/unload

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 2

$(window).unload( function () { alert("Bye now!"); } );
beforeunload
$(window).on('beforeunload', function(){ alert ('Bye now')});

as per jQuery docs "Most browsers will ignore calls to alert(), confirm() and prompt()" api.jquery.com/unload

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 2

OK, you're correct Syn doesn't do that correctly, and I can guess why -- the browser can't tell your keyboard layout (see here: detect keyboard layout with javascript) so it really can't tell what you should get for Shift+1, so it just gives you a '1'.

You would assume that

Syn.type('[shift]![shift-up]', 'textInput2');

Would work as expected but that doesn't either ... I think that's a bug in Syn.

So, can you do it in raw JavaScript? I can get close.

Apparently it's pretty hard to get it working cross-browser and this led me down a rabbit-hole of trying different things. First I looked at this question: Is it possible to simulate key press events programmatically? but that didn't work correctly in chrome, then I tried various combinations of events and values based on their documentation without much more success. Then I found this question: Firing a keyboard event on Chrome which led me to this code.

Pasting that code into the JS and then calling it with:

var e = crossBrowser_initKeyboardEvent("keypress", {"key": 1, "char": "!", shiftKey: true})
document.getElementById('textInput2').dispatchEvent(e);

Will give the output you expect. However, it doesn't actually write the value into the input box. Of course you could fake that and just add the text there as well, I'm not sure if that's a limitation in the way events work or if there's just something wrong with the code. Of course, for test, that might be all you need.

Here's the fiddle, maybe someone else can make the final jump.

javascript - Simulate shift + 1 keyboard event and retrieve it in a ev...

javascript unit-testing keyboard-events syn
Rectangle 27 2

$modal.open(tempModalDefaults).result

is a promise. When the backdrop option is set to 'true', the promise will be rejected. You can can attach a rejection handler to that promise by using either the then method or the catch method which is shortcut:

return $modal.open(tempModalDefaults).result.catch(function (reason) {
    // your code to handle rejection of the promise.
    if (reason === 'backdrop') {
        // do something
    }
});

javascript - How to detect closing a modal window in $modal? angular-u...

javascript jquery angularjs angular-ui