I was working on a WordPress project which i need to clear the PHP session when the browser or browser tab is closed. Although Javascript provides the window.onbeforeunload event but it will be triggered even whenever you leave the website. Finally i got a simple solution from Daniel Melo in StackOverflow. The following code required jQuery and i have included the Google one in the HTML.
In your web root, create the js/check_browser_close.js.
/** * This javascript file checks for the brower/browser tab action. * It is based on the file menstioned by Daniel Melo. * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed */ var validNavigation = false; function endSession() { // Browser or broswer tab is closed // Do sth here ... alert("bye"); } function wireUpEvents() { /* * For a list of events that triggers onbeforeunload on IE * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx */ window.onbeforeunload = function() { if (!validNavigation) { endSession(); } } // Attach the event keypress to exclude the F5 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; }); } // Wire up the events as soon as the DOM tree is ready $(document).ready(function() { wireUpEvents(); });
Also create the following .html in your web root to test the above Javascript file.
<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript" src="js/check_browser_close.js"></script> </head> <body> <h1>Eureka!</h1> <a href="http://www.google.com">Google</a> <a href="http://www.yahoo.com">Yahoo</a> <a href="https://ykyuen.wordpress.com">Eureka!</a> </body> </html>
A alert box will be shown when you closed the browser or the browser tab.
Done =)
Reference:
- StackOverflow – Close/kill the session when the browser or tab is closed
- StackOverflow – Kill sessions on browser/tab close
Update @ 2012-02-19: In Chrome, window.onbeforeunload is required to return a string. Please try the following check_browser_close.js.
/** * This javascript file checks for the brower/browser tab action. * It is based on the file menstioned by Daniel Melo. * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed */ var validNavigation = false; function wireUpEvents() { /** * For a list of events that triggers onbeforeunload on IE * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx * * onbeforeunload for IE and chrome * check http://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery */ var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave without confirmation var leave_message = 'You sure you want to leave?' function goodbye(e) { if (!validNavigation) { if (dont_confirm_leave!==1) { if(!e) e = window.event; //e.cancelBubble is supported by IE - this will kill the bubbling process. e.cancelBubble = true; e.returnValue = leave_message; //e.stopPropagation works in Firefox. if (e.stopPropagation) { e.stopPropagation(); e.preventDefault(); } //return works for Chrome and Safari return leave_message; } } } window.onbeforeunload=goodbye; // Attach the event keypress to exclude the F5 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; }); } // Wire up the events as soon as the DOM tree is ready $(document).ready(function() { wireUpEvents(); });
Update @ 2012-06-15: If there is any link which implements ajax feature, you can refer to this approach. Thanks Immo. =)
Update @ 2015-12-01: If you want to handle the refresh button, please refer to the comment made by Sandesh Satyal. Thanks Sandesh. =)
Reference: StackOverflow – Setting onbeforeunload on body element in Chrome and IE using jQuery
Thank you very much. I was looking for this solution.
LikeLike
good to know that it could help you =)
LikeLike
Ykyuen,
Is there a way to have a exception for page refresh (F5)
LikeLike
I have included the F5 press exception in check_browser_close.js
But this only works for user who press the F5 button, if the user click the refresh button using the mouse, the endSession() will be stilled fired.
hope this help. =)
LikeLike
yes u can use this code:
LikeLiked by 1 person
yes, it works for f5 but not the browser refresh btn.
LikeLike
I have searched for a working script quite some time, this seems to be the only one that works. Thanks.
LikeLike
good to know that it could help =D
LikeLike
Hi, I works for me, I’m closing the session on tab/ browser close. If user clicks “stay on page” option i don’t want to do any action.
Is there any way?
LikeLike
No action will be taken if u click “stay on page”.
what action did u find?
LikeLike
Hi,
Thanks for this solution it works great in Chrome and Safari. But in Mozilla Firefox, custom message is not shown. Please provide a solution if any in case of Firefox.
Thanks
LikeLike
This post is quite old and right now there is no a generic solution to solve it.
There are a lot of comments regarding whether it works on different browsers. maybe you could try to search it and you may able to find a solution.
LikeLike
awesome, it realy help my job, thank you so much…
LikeLike
You are welcome. =D
LikeLike
anyway to tell difference between a refresh, back and close window click?
best example out there
Thanks
LikeLike
you are welcome.
i think you can find some examples for detecting the browser back button @ StackOverflow – Detecting Back Button/Hash Change in URL
Hope it could help. =)
LikeLike
This was a real help….Am a pretty newbie,…I just had requirement….
I want to update a my SQL database and set the status of an online user to ‘0’ from ‘1’ from the function endsession()….i am stuck here…I tried using an AJAX code here to run a update query but its not working…
Here is what i’ve done…
LikeLike
so the update query is inside localhost/close.php? does it work if you just enter this URL in browser?
If the above checking is positive, i guess there maybe some problem in your ajax request. Maybe you could try implement it in another way as follow.
Ajax – Simple Ajax GET Request
LikeLike
When You submit validnagivation becomes true. After submit when u close the browser your session wouldn’t be ended.
LikeLike
I have master page and i save data in content page and then do alt+F4 i want to refresh parent page. But it will not calling method endSession() but when i do postback and then do alt+F4 it will call endSession() and my parent page get refereshed.
function endSession() {
parent.window.opener.RefreshRiskGrid(); window.close();
}
Please give me suggestion.
Thanks in advance.
LikeLike
Maybe you could consider binding the alt+f4 key press action. The following is reference of binding multiple keypress actions.
Reference: StackOverflow – Bind Multiple Keys to Keypress Event
LikeLike
Thank you- this helped save me
LikeLike
Good to know that i can help. =)
LikeLike
Its not working when i close page in crome. I am using google crome version “15.0.874.106 m”.
LikeLike
so does it work in firefox?
LikeLike
in firefox works,,, but not in chrome,,tested with 17.0.963.56 m chrome version
LikeLike
Seems the window.onbeforeunload has different behavior in chrome. you can try the new check_browser_close.js.
hope it could solve ur problem.
LikeLiked by 2 people
cool,, your updated code works like a charm in chrome 🙂
LikeLike
good to know that it works for you. =)
LikeLike
Thanks for the great post, Following also works perfectly for me;
LikeLike
thanks your code. =)
LikeLike
This is not working in Opera and Google Chrome!! Please help.
LikeLike
How about the simple solution suggested by Dilhan?
LikeLike
Thank you very much. very great solution.
LikeLike
You are welcome. Good to know that this could help. =)
LikeLike
Tinks for this script … it really help 😉
LikeLike
Good to know that i could help. =)
LikeLike
Its working, but when do any postback in asp.net it break, so how can I skip postback ?
LikeLike
Sorry, what do u mean by postback?
LikeLike
I have form with image button, link button and Dropdown list, its working fine when click on link or any button, but when select dropdown, this event is called and application signout.
LikeLike
In that case you have to add an extra checking when user select the dropdown
LikeLike
HI
I was wondering , how I can use ur code and disable when someone click on the refresh button in ALL the browsers?
Is there a solution for that
Thanks
LikeLike
You can try to capture the F5 keypress event but noway to prevent the user from pressing the browser refresh button.
you can find more info in the following posts.
LikeLike
Hi ykyuen,
Thanks for this great script! I’m using it to load a survey of why the user is leaving the page without completing a form. It works great for this, but I’m having one problem. If the user tries to submit the form and fails because the form was incomplete, then closes the window, the alert no longer comes up. Please see here:
http://request4.info/grantham-survey-if-test.html
Close the page, an alert comes up. Then open the link again. Click Request Information (without filling anything in), and then close the page. Now the alert doesn’t come up. What do I need to do? I’m not changing the value of dont_confirm_leave anywhere… A big thanks in advance for your help!
–Kyle
LikeLike
When the user clicks the Request Information button, the validNavigation is set to TRUE even the form validation is not passed. That’s y the alert box didn’t come out when you close the page.
How do u implement the form validation?
One way to resolve ur problem is that whenever the validation is prompted, reset the validNavigation to FALSE.
LikeLike
Thanks, that did it! I had to do a settimeout for changing the validNavigation to false though – otherwise the validation function would return false and immediately reset validNavigation to true! Thanks again!
Also, could you possibly remove my last name from the original post? I’m not sure what I was thinking – I don’t like to use my full name 🙂 Thanks,
–Kyle
LikeLike
Good to know that you have solved the problem. i have removed your last name in your previous comment. =)
LikeLike
nice solution, but i have a problem to open exit survey after closing page. How can it implemented in chrome as it just return message after closing window. KIndly help on it.
LikeLike
you want to open a new browser window after closing the page?
you can use the following js
Reference: Javascript-Coder.com – Using the window.open method
LikeLike
Hi,
F5 keypress event is nothandled in IE, its still calling endsession method.
LikeLike
I wonder if the following could solve the problem
1. Change
To
OR
2. Adding this to the wireUpEvents().
Reference:
LikeLike
Thank u very much ykyuen, both solutions worked.
I’m facing with another silly problem hope you can give some idea about it.
My website is having some certificate problem, when I log’s in IE gives Information bar giving message “cannot display contents due to certicate errors” when I right click and choose option of “Display blocked content” it refreshes whole page. How can I capture the automatic page refresh of browser in the above javascriptcode?
Thanks,
KD
LikeLike
It seems that there is no way in Javascript to capture the “Display blocked content refresh”. It should be treated as normal refresh. Maybe you could try to solve the certificate problem.
LikeLike
not working on page browser reload. or when enter to refresh on address bar.
LikeLike
Probably there is no way to capture the browser reload button clicked as i stated in this comment.
But maybe you could consider using cookie to store the state.
StackOverflow – Detect Browser Refresh in Javascript
Hope this could help. =)
LikeLike
Page is closing if user press enter button or ctrl+f5 on page its call logout function.
LikeLike
Please refer to my reply above.
LikeLike
+
LikeLike
++
LikeLike
Hi ykyuen,
Have you found solution for browser back link, refresh button and enter on url ? I have added all conditions but could not find any solution for these 3 conditions ?
Any help is much appreciate.
LikeLike
Maybe you could try the cookie method in this comment.
About the enter on url, it should be handled by the following part.
LikeLike
where to use prompt box and ajax call ?
LikeLike
Sorry, can you elaborate more?
LikeLike
I have used the code in this way,it works fine in mozilla,but in chrome it doesnt works , if call endSession() inside function goodbye(e).
below is my code(i have commented goodbye(e) function here) ,can you help me out in this
LikeLike
It seems that the window.onbeforeunload in Chrome could only return a string and all other code are ignored.
StackOverflow – window.onbeforeunload not working in chrome
I am not sure if it is a bug or the Chrome dev team do it deliberately. Maybe you could submit the issue @ The Chromium Projects
LikeLike
Hi,
This post really helped me a lot. Thanks.
Similar to 116 keycode for F5, is there keycode for the Next and previous buttons in iphone’s virtual keypad
LikeLike
I couldn’t find the keycode of the next and previous buttons in iOS. Here is the keycode reference for iOS 4.
iOS keycodes in Javascript
Maybe you can use the following js code to detect the keycode.
Determining which key is pressed
LikeLike
Hi,
thanks for the code works well. I had to add one thing to handle navigation triggered by ajax requests. You don’t want to set validNavigation on all clicks on input elements as you might have a few of them which just cause a change in the page but not a navigation away from it. And if every click on a ‘ajax’ button or link sets validNavigation to true you wouldn’t be able to catch the back button anymore.
So what I did for ajax pages is to have validNavigation set to true on the start of an ajaxRequest (in the function ajaxReqStarted()) and back to false at the end (in the function ajaxReqFinished().
E.g. if you use RichFaces you can simply use the queue for a page (e.g. a global queue).
*fixed the syntax highlight by ykyuen
Regards
Immo
LikeLike
Mmh the code got deleted. Here it is again without the brackets
*fixed the syntax highlight by ykyuen
LikeLike
Your approach should be helpful to anyone who needs to work with ajax. Thanks for your code. =D
LikeLike
Bravo!. Great great geat solution. I was trying to implement this since 2 weeks, but everytime small problem killed my work. Now one more thing I need is to pop up on tab change. Can you help me plz. and thanx for your great work.
LikeLike
i guess u want to exclude the checking when user clicks the tab. Assume the tab is a <a> element, you can exclude it by sth like
where tab-id is the id of the <a> element. i.e.
<a href="#" id="tab-id">tab title</a>
LikeLike
Hi
Please upload the Update and final javascript..
Thanks a lots….
LikeLike
The Update @ 2012-02-19 is already the latest one.
LikeLike
Hi ykyuen,
This script is working great but i want to display alert only when i choose to close the browser tab or browser. Please help…
LikeLike
Unfortunately the window.onbeforeunload in Chrome needs a returned string and seems that it must display a 2 options alert box (Stay or Leave).
LikeLike
Hi! Thanks for this script. It really helped me a lot. Btw, is their a way that we could detect if the user clicks on the browser back, forward and reload button?
LikeLike
For browser back button, you can refer to this comment.
There is no way to detect the browser reload button.
LikeLike
Thanks for the quick reply..:)
LikeLike
you are welcome. =)
LikeLike
Thank you for your code!
Very cool sorce!!
LikeLike
thanks for your comment. =)
LikeLike
Thank you for your comment!
Unfortunately I got a problem.
It doesn’t work in Samsung GalaxyTab and GalaxyS.
In this case, how can i solve this problem?
LikeLike
Reference site: http://stackoverflow.com/questions/11257234/window-onbeforeunload-event-not-working-in-samsung-tab
LikeLike
i found 2 posts about the window.onbeforeunload in iOS safari.
Please note that there is no a generic way to handle it for all OSs and browsers. If you really need to make it work for all of them, probably you need to spend a lot of effort to handle difference scenarios.
LikeLike
Hi,
Great Solution!!! It works for me almost in all case except having a very small issue:
I have used this code on my ASP.Net Master Page and its working for all types of navigation and click events but when i open a new window from any hyperlink it doesn’t work.
Here is what I am trying to do:
MasterPage.master code:
Your updated piece of code placed in this.
Content Page Code having above master page.
/// a onclick=’ShowDocument(“/trial/Docs.aspx”)’
function ShowDocument(url) {
…..
…..
window.open(url, \”docwindow1\”, \”status=yes,toolbar=no,resizable=yes,menubar=no,scrollbars =yes,top=0,left=0\”);
}
So, when i close the new window and tries to close my main window it does not popup the message for confirmation.
LikeLike
you want the popup message appear on closing the new window or main window?
LikeLike
on main window..
LikeLike
i think u need to reset the validNavigation to false after the new window is opened. maybe add it at the end of ShowDocument.
does it solve the problem?
LikeLike
yes it solved my problem by resetting the validNavigation to false..
LikeLike
great. =)
LikeLike
This works perfectly.
LikeLike
thanks for your code. =)
LikeLike
TT I hava a problerm
only i can use this -> $(“a”).bind(“click”, function() .
f5, form, submit cant use TT
how can i solve?
LikeLike
for keypress: try using document without single quotes:
LikeLike
i want to update signout time in database when browser or window is closed..but problem is that when i click on back or forward button the signout time update in database even i am currently login..
so any solution for that..?
LikeLike
i think you can find some examples for detecting the browser back button @ StackOverflow – Detecting Back Button/Hash Change in URL
LikeLike
thanks for your reply but i don’t want to change url on clicking of back or forward button. i just only want to update signout time in database. for that i have try onbeforeunload event but that also call for the back and forward button.
LikeLike
is the update signout time implemented by your own code?
maybe you could use session to store if the user login status and then you check it before you update the database.
LikeLike
thanks for your reply..but i don’t want to change url on click of back or forward button..i just only want to update time in database and for that i have try onbeforeunload event but that call on click of back/forward button..so any solution regarding this..?
LikeLike
yes it’s my own code to update time in database..
but i want to implement such a thing that “user is log in but if he/she directly close browser or window then signout time update in database”…
LikeLike
sorry that i couldn’t help. there is no simple way to detect the browser back or forward button.
i would still suggest your to use session to check user login status.
LikeLike
How to handle the form submission through javascript and refresh events?
LikeLike
I meant browser meta refresh event
LikeLike
If you want to exclude the form submission thru javascript. just set
inside that submission function.
I am not very sure what is a meta refresh event. could u paste your code here? Please follow the Syntax Highlight to paste the code.
LikeLike
Thanks for reply it worked :)…below is code I was referring in my previous comment for refresing the page at a specific interval:
LikeLike
Great. good to know that u have solved the problem. =D
LikeLike
For those wanting to do ajax before unload you need to do a synchronous ajax call
LikeLike
Thx. =)
LikeLike
Can i use custom message? rather than – Are you sure you want to leave this page?
N i want to give link in custom alert box. any idea for this?
LikeLike
You can customize it by editing this string.
But for some browsers, the leaving dialogue is a default msg which cannot be modified.
LikeLike
yes. In chrome they use their message. And we can’t give link in leave box right na?
LikeLike
Ya, i guess we could not change that msg.
And Javascript alert box does not support hyperlink. But there are other method to implement it in another way. The following link should be useful for you.
StackOverflow – Link in Javascript alert
LikeLike
Lo utilizo en PHP. Si el usuario abandona la página carga otra donde actualiza una base de datos. Luego de actulizar los datos cierra la página.
I use whit PHP.
If user leave the page it load another where it update database, then close itself.
(DelLogged.php)
Saliendo…
Funciona en chrome y firefox.
It’s works under chrome and firefox
Gracias
Thanks
LikeLike
Thanks for your suggestion. Gracias =D
LikeLike
I wish to display a form in order to update the database only if the user confirms that he wants to close the window. However, I am unable to track the event on confirmation of the close message in spite of implementing all the above possibilities.
Please help, since I am unable to proceed.
LikeLike
I think that will be quite complicated. Here is my suggestion.
When the user close the message, you have to send a ajax request to the server in order to update the database, probably you will need some authentication here other wise it will be spammed.
LikeLike
This is a really nice solution. This can be used for some kind of one time password scenarios for example i log in with my one time password and if i close browser that one time password must be refreshed and overwritten with a new one. Thank you 😉
LikeLike
You are welcome and thx for your comment. =D
LikeLike
hi ykyuen this is a really nice solution and the best I have seen. Can you give me a suggestion on whether it is possible to track user click “Yes” and call some function (i.e update logout time upon confirmation)?
LikeLike
you can use the window.onunload. for example, add the following line in the .js.
If you click Yes, the window.onunload will be triggered. The above code will open a new window showing this blog.
Hope this help. =)
LikeLike
hi thanks for your quick response. I have attached your js file to one of my projects. It is an asp.net project. In the home page it has dynamically loaded menus and a dashboard which consists of grids. When I click menu item or hyperlink within the grid (these are created dynamically) ‘You sure you want to leave’ message is displayed.Can you suggest me how to bind the proper event in js file to avoid this message?
LikeLike
Hi Samitha,
how do you load the menu and dashboard dynamically? is it done by js?
If yes, try loading the check_browser_close.js at the end. i.e.
Does it solve the problem?
LikeLike
Hi I am not loading the menu from a js. It’s done the code behind. Anyway I moved the ,js reference just after the closing html tag and it seems working fine. I have read at some other place that window.unload event doesn’t fire on IE. Somehow the way you have suggested working fine and satisfies my requirement. Thanks for your prompt reply and keep up the good work 🙂
LikeLike
Good to know that you have solved the problem. =D
LikeLike
Hi! How do you know if the user clicks on “accept” or “cancel” ?
LikeLike
You could add the implementation of the window.onunload event in the .js file.
LikeLike
Hello! great script but I have a problem with firefox.
If i push the refresh button or when i klik on a menulink the function window.onunload = function(){ window.open(‘http://www.google.nl’); }; is always happening.
It looks like I can’t disable the script for refresh and links.
You know what I should do?
LikeLike
Hello again,
This solved the isseu.
function ShowDocument(url) {
var mywindow = window.open(“http://www.google.nl”);
mywindow.onunload = function(e) { validNavigation = false;};
}
LikeLike
O no did not solve it just workt one time maybe i did not refresh page.
LikeLike
There is no simple way to detect the browser refresh button. please refer to this comment.
For menu link click, i think u need to detect it by js and then set the validNavigation to true.
Hope this help. =)
LikeLike
Hello Ykyuen,
Thanks for your answer helps allot.
Can I ask you for a fafor I realy do not want my e-mail adress displayed public and also not my website could you please remove it from the public acces?
I did not see that it would come publicly avalible.
I found great use for your plugin and i am very glad with your solution thanks.
LikeLike
I have removed the url and email address. =)
LikeLike
Thanks for that,
I don’t have any time to work on your script for a while but I did do some work on it and thought lets share.
I found a way to tell people what to do if the use the refresch button or any other browser navigation buttons also I found a way to make the menu links not respond on your scipt and a way to redirect to a sertain page it now only works in IE and Firefox.
For Opera Safari and Chorme I still got to make it work but as I said I Need to do some other stuff first. But I will post it here for anyone who needs it.
I dont know How to put code on here so I try but dont know if it go’s oke. Here it comes.
———————————————————————————-
LikeLike
Thanks for your code but seems that there is a missing bracket on line 110. Could u follow the Syntax Highlight and post it again? Thanks. =D
LikeLike
Hello Ykyuen,
Dreamweaver does not see the missing bracket on line 110 so the have to look into this when the use this code any way it seems also to work without that bracket and i am sorry but i am not able to take a futer look at this right now. But i will post it again and use the syntax highlighting you told my about. If you like you can remove the code without the syntax higlighting. Thanks again for your great code. here it comes
———————————————————————————————–
LikeLike
It’s ok~ thanks again for your code~ =D
and i hv updated line 61.
LikeLike
Hello Ykyuen,
I had a litle bit of time and could do some more work on your code. Can you please remove my tree previous posts I mean the ones with The code.I Have cleared some unnecessary junk lines. I also found a way to make it work in Google Chrome and safari. So now it is working in Google Chrome, IE9, Safari en Firefox. Next time I will look at Opera. Here is the new code: Works like a charme
————————————————————————
LikeLike
Thanks for your effort. you could keep posting and i will summarize it on this blog post once the code is finalized. =D
LikeLike
Hey D,
I will spear you the summerize part and post once the code is finalized. Thanks this blog is realy helpfull.
LikeLike
Hi Ykyuen, very nice script, congratulations!
But I have 2 problems…
1 – The script is not working in Opera.
2 – I wish to call a function “logout” when the user confirms the closing of the window.
Can you help me?
LikeLike
Hi AGoes,
1 – The script is not working in Opera.
Currently Jeroen is working on a better solution and he is still working for Opera. I am sorry that i am not going to dig deeper to the solution since looking for 100% compatibility on this requirement is a bit too far for me. especially when different browsers have different responses on the input.
2 – I wish to call a function “logout” when the user confirms the closing of the window.
There is no way to do that. we couldn’t know whether the user pressed stay or leave. you can refer to this comment.
LikeLike
Hello AGoes,
You can call the function I believe if you put it between the if (X) or if ( x == true) parts where the url’s are. Opera may be a problem it does not know a onbeforeunload event it does how ever know the onunlaod event so I will take a look at that when i have time.
Use the code just above this text than you can call a function or url.
LikeLike
thanks for your clarification~ i didn’t know you have solved the 2nd question. =P
LikeLike
Hello there, I did take a look at opera but it does not like to detect the close tab event. So I made up a different way to detect a close tab. just ask. This code opens a seccond window when you close the second window a allert box ask you if you want to end the session. then you get redirected to the end session page. here is this code.
LikeLike
Thanks for the script and it is working for IE, firefox and chrome. I have lot of pages in my web application. Can I have any option to define close browser and close tab in one place for all the pages?
LikeLike
You can put all the inline code into a .js file and then include it inside the <head>.
LikeLike
Thanks for the reply.
But, this is for each page which means we need to include in each . Right?
LikeLike
yes, you need to include it on each page.
LikeLike
Hello ykyuen
I’m Momin Ansari from Mumbai,India
I have a Problem regarding Browser Closing…….
See I have a Master Page and inside that have so many Pages which contains many user controls….Now I want a piece of code eg yours if I put on the Master Page and while Navigation it won’t display the Message Box na….Suppose If I Navigate “A.aspx” and close the Browser then it will display the Message…and if I Navigate to “B.aspx” then it won’t Display the Message…I hope so that you will understand my problem……..Waiting for your reply…..
LikeLike
Hello,
If the browser crashes (or) killed explicitly by the user, I would need to have control for this to send to the server.
Is there a way of doing this?
Thanks
Praveen
LikeLike
Hi Praveen,
I tried to close the page by terminating the browser in task manager and the alert dialogue was prompted. so i think you can still make use of it and send a request to the server thru ajax.
LikeLike
As u read in the code, it tries to disable the message box for specific action by setting validNavigation to true. e.x.
So i suggest you could set a specific class to the elements in the .aspx.
For example, if you want to disable the message box for all hyperlinks in B.aspx. then you can add a class to it, say
Then in the .js, add the following piece of code.
So any hyperlink with class “no-message-box” will not trigger the message box.
LikeLike
Sir what about Menu Controls like I have a Parent Menu and inside that I have many Child menus so when I navigate to menus it sholudn’t display the Message and when i close the Page then it should fire a Page methods/AjAX Request…..plz let me know….Waiting for your reply……
LikeLike
So just add the class to the child menu items in order to disable the alert message box.
LikeLike
But Sir,,,
The Menu Items are coming from the SiteMap….i.e in Web.SiteMap we had specified the URL like
so how to Manage……Plz Sir Help me out I’m stuck in this for the last 2-3 days
LikeLike
If you couldn’t add the class to the menu item. maybe you could use jQuery to add the class and then bind the click function to set the validNavigation to true.
If still doesn’t work, then I think you need to use a proper jQuery selection to select the menu item.
LikeLike
and one more thing I’m using the following code
window.onbeforeunload = function() { myUnloadEvent(); }
function myUnloadEvent() {
PageMethods.TestMethod();
}
where TestMethod() is the WebService called when the Browser is closed….N
Now my problem is When I navigate to TreeViewNode and click on some Link it doesn’t get Fired…….Plz Sir guide me in this
LikeLike
I guess you may have some links which will not trigger a page refresh. in that case, u have to reset the validNavigation to FALSE.
LikeLike
LikeLike
Thanks for the code. =)
LikeLike
hi,i want to open popup box with one form at same window when i close tab,and in that popup user able to fill a form.pls help me..Thanks in advance.
LikeLike
You can prepare the form in another url and open it up in a new browser window. You can refer to this comment.
LikeLike
thanks for your work but it is still not working in Opera
I tried the code of Jeroen but it’s not working
I hope you can help me
LikeLike
Hello, Did you try this code here? Jeroen on December 1, 2012 at 03:50 said: Opera doesnot support windowunload event or window close so this is the only way I could think of. here is the code:
LikeLike
You can log in here and see what the code does in Opera.
And the other browsers.
http://www.terraverdedesign.nl/
Usernaam: geust
Password: loveit
LikeLike
" = is wrong it just needs to be: “
LikeLike
Hi, I tried to use this script to detect if browser close button is clicked.
In my application there are submit buttons, links and other controls.
As I see, sometimes onbeforeunload function runs before controlling “validNavigation”.
Do you have any idea how to resolve it?
LikeLike
Thit u use this?
LikeLike
I will open a new browser if user closes the browser. I use almost same code as yours to handle browser close event. But sometimes, it opens a new window even if I click a button or link in my application. I debug in firefox and see that, it doesn’t always assing true to validNavigation parameter.
I hope you can help me.
LikeLike
Hi Ykyuen,
thanks for the code works well. I had to add one thing to handle navigation triggered by window.location.href.
LikeLike
(JEROEN says) Hello I use this code:
LikeLike
Opps i see i posted the dutch version here is the english version!”
LikeLike
This version works in Opera, Safari, Firefox, Internet explorer and Chroom
LikeLike
Hi Jeroen,
Is it possible to get rid of confirm messages in chrome browser. I think it is confused and not comfortable for end user. Is there any way to end session through onbeforeunload method for Chrome browser like Firefox/IE.
I user following code for firefox and IE:
here section is expired in IE and FF.
Please suggest me how can get this in chrome browser.
LikeLike
I guess the confirm messages of chrome browser is the return messages. how about doing a redirect before the return?
LikeLike
I need to use this script only if user spend < 60 seconds on my site, if this user is our regular customer i dont want to worry him with this message . I'm trying to make js all day, but i cant. May be someone can help me?
LikeLike
You can schedule a function using setTimeout() and set validNavigation = true.
sth like
Reference: jQuery & Javascript – Schedule a Function call by setTimeout()
LikeLike
can anyone reply,what to do when i want to delete a file on window/tab close? i am using ajax for this
where to put my ajax code in this case?
LikeLike
In the example of this post, you can try
But your POST request will send to server anyway no matter the user click stay or leave.
LikeLike
Hi ykyuen,
Great Script !!! but is there a way to use this script, just on Browser close only and not every page refresh, right now “You sure you want to leave?” alert is coming on very page refresh as well as on Browser close event…..i just want to use this on Browser close and not on refrsh event.
LikeLike
Hi Amit, as far as i know, there is no way to bypass the checking of the browser refresh button. There is sth out of the control by Javascript.
LikeLike
Hi Friend..
Good Script..
I am Using below code…
————————————————————————–
——————————————————————————
its work great..problem is when i press input type button its giving a endsession method alert message…its should not come..
when i press input button i am redirecting to another page (using onclick method & redirecting using document.forms[0].submit)
Please give a solution asap..
Thank u
LikeLike
is your input type = “button”? if yes, you could bypass it by adding
LikeLike
One thing needs to be corrected though concerning the F5 keypress. Some browsers *cough* IE *cough* will not react on keypress but will react on keydown so that would be a better choice. Also the quotation marks around document stop it from working. it sould be
$(document) not $(‘document’)
LikeLike
Thanks for pointing out the mistake. i have updated the post. =)
LikeLike
Thanks for posting this – is the code you provided up to date with all the fixes and suggestions posted via comments over the years? If not, could you provide a js file that is updated available for download?
LikeLike
Hi Mark, Jerome has made the script works in opera. you could refer to this comment. hope it could help.
LikeLike
I’m using Ajax in some pages…and when I click in some ajax request the code dont work because validNavigation is set to true.
Can you help me with that?
LikeLike
you can add an id on those anchor and exclude them by
Does it work?
LikeLike
Great post. You should add it to Github
LikeLike
Yes~ will do later. thanks for your suggestion. =D
LikeLike
Great Post, But can you provide me the complete Snippet some where downloadable/ even with AJAX involvement for dynamic script.
LikeLike
Hi, can you please even clear this line it is generate an error –
window.onunload = document.location = (“http://www.terraverdedesign.nl/session_end.html" ;
LikeLike
Hi Prashant,
You can refer to this comment for the code snippet provided by Jeroen. I haven’t tried to run the code before and i think the code is specifically for Jeroen own use so i think you could just edit it such that it works for you.
Maybe i will create a github repo for this example later.
Thanks for your comment. =)
Kit
LikeLike
How to use AJAX because I am try all example as given above but there is no any change in DB by AJAX, so please provide me the snippet,
LikeLike
Hello
I am using the version (Update @ 2012-02-19) script. Implemented simple ajax call to a page that just destroys the session.
Everything works properly, when closing tabs, etc. …
But I’m having problems with the F5 (Refresh), even as the script by default ignores the F5, whenever I press this button, activates the alert message and closes my session because he understands that it was like a close tab action.
Any solution?
It happens in all browsers.
LikeLike
The f5 key is handled by this checking
But if you are using a mac machine the keycode maybe different. you can try adding alert(e.keyCode) and see the keycode value. you may also need to check the e.metaKey. For more info, you can refer to the following post.
StackOverflow – How does one capture a Mac’s command key via Javascript?
LikeLike
I cannot get this test included in the wireupevents script, I’ve tried $(‘tr’).on(‘click’ – $(“.rows”) – and a few others. Any ideas?
LikeLike
sorry, i couldn’t get it. could u elaborate more? also, if u want to post code snippet, you could follow the instruction @ Syntax Highlight.
LikeLike
Hi, Something got lost in my post.
I want to include the onclick event in the exclusion script as you have for .
test
I have tried
$(“tr”).on(“click”, function() {
validNavigation = true;
});
LikeLike
I’ll try again
LikeLike
try adding
inside the wireUpEvents().
And you could add alert() inside the click event so you can confirm if the event is fired or not.
LikeLike
Sorry – my previous explanation a bit confusing.
My problem is , I tried this and it does not fire.
LikeLike
Hi – After even more testing it looks like it does fire but AFTER the onbeforeunload event.
LikeLike
Found a workaround – added
LikeLike
LikeLike
Good to know that you have found the solution~ =)
LikeLike
dude I cant thank you enough
LikeLike
No thanks. =D
LikeLike
Reblogged this on Ganesh Kunwar's.
LikeLike
this code works for me but the problem arises when there is a reload page function as when page is reloaded with value it got disconnected
LikeLike
in that case you need to make use of cookie to keep tracking the status. Please refer to this comment for more information.
LikeLike
Hello! This is my first visit to your blog!
We are a team of volunteers and starting a new initiative in a community in the same niche.
Your blog provided us beneficial information to work
on. You have done a outstanding job!
LikeLike
Good to know that it helps~ =)
LikeLike
Hi,
Thanks for this. I have a question though, I can’t seem to prevent the onbeforeunload event message when I post via iframe target.
I have this form to submit a file and is posting on an iframe target. I keep getting the alert message of leaving or staying in Chrome. If I stay the form doesn’t get submitted. I wanted to prevent the message and keep on the form submission.
Would you know if there’s a way? Thank you so much.
LikeLike
add the following in the wireUpEvents(), does it work?
LikeLike
Hi all
Below code is working for latest chrome(Version 35.0.1916.114 m), firefox(28.0) and also works in IE(11.0.96…….)
LikeLike
taken from
http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser
LikeLike
Thanks for your update. =)
LikeLike
Hi,
My scenario is as follows. I have a registration form and only when the user try to close the browser / tab and navigate to other domains it should show the navigation conformation box.
In this registration form I have modal popup which has an <a> link and when I click on that it asks for the page navigation confirmation which don’t need as it will redirect to some other page.
I have added the below bindings to the js file.
Thanks in advance.
Arul
LikeLike
if the modal popup is created after you load the js files, the event handler could not be binded. you can make use of the jquery .on() and bind the event handler to the any parent html element which exists before you load the js files. Ex.
LikeLike
Hi All,
Problem on browser reload,refresh from mouse the logout actions is being called.
Testing on latest chrome(Version 35.0.1916.114 m), firefox(28.0) and in IE(11.0.96…….)
How to restrict browser reload on chrome and refresh on IE etc.
can anyone help?
Please give suggestions if anyone faces this type of problem.
LikeLike
Hi Parvez,
Seems there is no way to capture the user click on the browser refresh button, but you can escape the “f5” key. You can refer to my previous comment.
Kit
LikeLike
Hi, I have one question. I want to do redirect to other page, when somebody chose “Stay at page”, any ideas ?
LikeLike
See if the following post helps.
StackOverflow – using onbeforeunload event, url change on selecting stay on this page
LikeLike
thanks for your help !!!!!
LikeLike
how we detect browser close , tab close and back and forward button event in javascript when event is performed on mouse click event?
LikeLike
also add some browser reload button event on mouse click?
LikeLike
those browser buttons (back, forward, reload… etc) even being clicked by the mouse could not be captured by Javascript.
LikeLike
HI Thanks,
The script you all mentioned above is working but onbeforeunload event is being fired on browser close as well as on page refresh. Is there any way to fire this event only on browser close not on page refresh. For F4 and CTRL+F4 we can trace key code and prevent them but what to do in case of browser refresh button click or if someonel click in address bar and press enter. In these cases your script is not working. I would appreciate any help in it. Looking forward to hear you you.
LikeLike
Please refer to my previous comment.
LikeLike
Can we detect back & foward button and then we will not display message. The message only display when user click on close button of the browser? It can be?
LikeLike
I think that cannot be done.
LikeLike
Hi all,
I’ve make like that, but I cannot handle event (back, foward, reload ) in browser bar.
could anyone help me about it.
thank in advance.
LikeLike
Seems no way for capturing the browser button effect.
LikeLike
i want record time duration from Once play video in web by clicking play button(built-in or player screen)
i don’t know which event should i take???
LikeLike
This may help
Javascript – Determine which event is triggered
LikeLike
Hi will this trigger change of page using php header function?
LikeLike
I think so but i am not sure your use case. Since in this example everything occurs on the client side and has no on control on the server side.
LikeLike
Hi guys, this very good article which is helped me a lot. But one small issue which i am facing mentioned below
Case Documents:
I want to handle above click event. Its always asking “what to leave this page”. How to handle this?
Please help me your suggestion. Thanks in Advance
LikeLike
how to handle this click event?
LikeLike
try this
LikeLike
Thanks for your reply. But i can’t do like this way due to N’number of places need to modify. Is there any other way to do it in one place
LikeLike
I guess that is the only way, because the onclick attribute will be executed first before any event listener bound to the element.
you have to refractor your code say calling a javascript function in onclick such that you have more control on that entry point.
ex.
LikeLike
Hi, Thank you very much for this nice n easy solution. I have one problem.
I want to perform two different operations when user selects leave page or stay on page. how can i detect what user has selected so as to perform respective operation?
LikeLike
seems no simple way to achieve that.
LikeLike
I Close the Browser the database value can be changed the session value not deleted …….give me your suggestion
LikeLike
i don’t understand your question, can you elaborate more?
LikeLike
Hi ykyuen,
Is there a way to seperate the back, forward, refresh and close button ?
I read your article from the start and I still research the solution but it dead end for me.
Can you help me.
Thank you very much.
LikeLike
i think there is no way to capture the events of the back, forward and refresh buttons of the browsers.
LikeLike
hi is there a way to stop the back and the reload button in browsers . using the before load event . i am trackin the custumer transaction .each step and checking and sending mail .each step . if he closes window and leaves transaction pages .
LikeLike
As i mentioned in the previous comments there is no way to handle the back or the reload button of the browser. You can try searching the recent posts in google and see if there is any breakthru in the past few months.
LikeLike
Hi,
I have a question from you post below, in the confirmation message asking if I want to leave the page and the I hit “leave” button and then the browser closed, is it possible to call, like, logout.php of mine which will kill all the session after the browser is closed? if so, where will I put it.
Many Thanks,
By the way this post has been very helpful already!
Good Job!
LikeLike
Hi, this is what I meant, so if the browser/tab is closed and then the confirmation message was clicked is it possible to call a page.php afterwards? page.php will kill all session active.
LikeLike
Does this comment help?
LikeLike
Add this code somewhere and the script will be complete, this solves the problem of refresh button.
Derieved from Bipin Mallik code from stackoverflow:
url: http://stackoverflow.com/questions/18457797/how-to-know-whether-refresh-button-or-browser-back-button-is-clicked-in-firefox
LikeLike
Thanks for your snippet. =D
LikeLike
I copied Same code but its not working…! 😦
LikeLike
The code may not work for latest browsers. Try the code snippets from the comments.
LikeLike
Hi.I tried your code but in Chrome when i close the browser it opens a confirm navigation alert box and on selecting ‘Leave This Page’ I want to call the endSession(); method where i will be clearing the session.. How can i do that? You are just returning the leave message in the code. Can you please help
LikeLike
Hi.. I tried using your code. When i close the browser in Chrome it prompts me to Leave the page and upon clicking that i want to call a endSession() function which will actually hit the server and invalidate the session. Can you please tell me how i can do that?
Appreciate your help.
Thanks
LikeLike
If you don’t need to prompt for user confirmation, you can just remove those validation checking logic and bind that function to the window.beforeunload event.
but i dun think using ajax will work because it is async and the browser will close the tab before the server returns the response to the browser. you should consider making a synchronise request.
LikeLike
Thanks for your reply. So you mean i can remove the below function goodbye and instead call my endSession() which will do a synchronous request to the server to invalidate the session like this?
LikeLike
Kindly ignore my previous comment. This is what i mean.
So you mean i can remove the below function goodbye and instead call my endSession() which will do a synchronous request to the server to invalidate the session like this?
Thanks
LikeLike
yes. does it work?
LikeLike
Hi. Yes it worked.. I did it this way and it worked in Chrome:
Thanks
LikeLike
Cool~ glad to know that. =D
LikeLike
Thank you skyzoninfotech! Worked for me on last Mozilla Firefox Release (45.0) on Ubuntu Linux, now I test it on Windows 7 (Internet Explorer), I’m praying for …
LikeLike
Actually this is not a full fletched solution. This logs out even when you click on browser refresh button or change the url which is not desirable.. Can anyone please provide a solution for that?
LikeLike
Hi,
Can anyone tell me how to prevent every time asking prompt? if run url, then it will ask me prompt “Are you sure want to leave this page?” without closing browser or browser tab.
I have used below code:
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
http://check_browser_close.js
Eureka!
Google
Yahoo
Eureka!
I have also check check_browser_close.js file for that but i coudn’t get any solution.
Also I want to put prompt before user will click on Logout link. Is it possible to ask before logout session?
Can anyone help me to find solutions?
Thanks.
LikeLike
Hi,
I have added HTML code but it not visible in post.
Now i am adding HTML code:
Please check above code and I have used same check_browser_close.js file.
Let me know further information.
Thanks.
LikeLike
The prompt is created by
window.onbeforeunload=goodbye;
, you can useif else
to determine whether it should prompt or not.Bind the click function to your logout link such that it will prompt. ex:
LikeLike
Not working in firefox, I have used the chrome version js which is working fine in IE and chrome but not in FF
LikeLike
For jQuery 1.11 :
Use keydown instead of keypress for F5 key..
In keypress event keycode is differen and F1->F12 keys doesn’t have one
LikeLike
this considers pressing the back arrow and forward arrow as non-valid navigation, also same for alt+back and alt+forward.
LikeLike
where do you put this code. in inetpub?
LikeLike
great work, thank you so much 🙂 🙂 🙂
LikeLike
thank you very much. I have always sought this solution.. you saved my life
LikeLike
In Chrome works only refreshing page. When I close tab nothing happens.
LikeLike
I am not able to handle page refresh. on every page refresh it prompts the message.
Can anyone help me on this?
LikeLike
Thank you. You helped me. One Question? Is there any way to show customized pop up instead of the browser pop up?
LikeLike
I am stuck. Can you help me? please share the code if you can.
Thanks.
LikeLike
Hi Anuradha,
I am stuck. Can you please share the code, if you can
My email is it.sunil77@gmail.com
Thanks,
Sunil
LikeLike
Hi,
I used the given code here without any change. It doesn’t show pop when reloading it.
LikeLike
Hello,
Use the code to control when the user clicks on (x) of the browser so that I log out of my database and it works well in development, I am using asp.net c #, the problem is when I publish it on the server simply not does nothing, I have referenced the js in the following ways:
http://~/Scripts/Cerrar_Web.js
https://miServidor/Scripts/Cerrar_Web.js
I put the code in case someone needs to do the same, create a web method on the page to be responsible for the change in the database, the problem is to publish it, why not execute the * .js?
LikeLike
we can find how many url open over site using jquery and java script or php.
LikeLike
Good day. I’m having trouble it seems that it is working in asp.net mvc 5 need help.
LikeLike
Is this question still active in this forum?
LikeLike