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="http://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 withou 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. =)
Reference: StackOverflow – Setting onbeforeunload on body element in Chrome and IE using jQuery
Thank you very much. I was looking for this solution.
good to know that it could help you =)
Ykyuen,
Is there a way to have a exception for page refresh (F5)
I have included the F5 press exception in check_browser_close.js
... // Attach the event keypress to exclude the F5 refresh $('html').bind('keypress', function(e) { if (e.keyCode == 116){ validNavigation = true; } }); ...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. =)
I have searched for a working script quite some time, this seems to be the only one that works. Thanks.
good to know that it could help =D
awesome, it realy help my job, thank you so much…
You are welcome. =D
anyway to tell difference between a refresh, back and close window click?
best example out there
Thanks
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. =)
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…
var validNavigation = false; function endSession() { // Browser or broswer tab is closed // Do sth here ... alert("You are about to close your page and session"); var xmlhttp; URL = 'localhost/close.php?id=3'; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("PC").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET",URL,false); xmlhttp.send(); } 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 $('html').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(); });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
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.
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
Thank you- this helped save me
Good to know that i can help. =)
Its not working when i close page in crome. I am using google crome version “15.0.874.106 m”.
so does it work in firefox?
in firefox works,,, but not in chrome,,tested with 17.0.963.56 m chrome version
Seems the window.onbeforeunload has different behavior in chrome. you can try the new check_browser_close.js.
hope it could solve ur problem.
cool,, your updated code works like a charm in chrome
good to know that it works for you. =)
Pingback: Browser window close and tab close
Thanks for the great post, Following also works perfectly for me;
$(window).unload(function() { if(event.clientY < 0) { closePage(); } });thanks your code. =)
This is not working in Opera and Google Chrome!! Please help.
How about the simple solution suggested by Dilhan?
Thank you very much. very great solution.
You are welcome. Good to know that this could help. =)
Tinks for this script … it really help
Good to know that i could help. =)
Its working, but when do any postback in asp.net it break, so how can I skip postback ?
Sorry, what do u mean by postback?
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.
In that case you have to add an extra checking when user select the dropdown
... // Attach the event click for all inputs in the page $("input[type=submit]").bind("click", function() { validNavigation = true; }); // Attach the event when the dropdown option is changed $("select#select-id").bind("change", function() { validNavigation = true; }); ...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
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.
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
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.
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
Good to know that you have solved the problem. i have removed your last name in your previous comment. =)
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.
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
Hi,
F5 keypress event is nothandled in IE, its still calling endsession method.
I wonder if the following could solve the problem
1. Change
$('html').bind('keypress', function(e) { if (e.keyCode == 116){ validNavigation = true; } });To
$('document').bind('keydown', function(e) { if (e.keyCode == 116){ validNavigation = true; } });OR
2. Adding this to the wireUpEvents().
document.onkeydown = function disableKeys() { if( typeof event != 'undefined' ) { if(event.keyCode == 116) { validNavigation = true; event.keyCode = 0; //return false; //return false if u want to disable refresh } } };Reference:
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
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.
not working on page browser reload. or when enter to refresh on address bar.
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. =)
Page is closing if user press enter button or ctrl+f5 on page its call logout function.
Please refer to my reply above.
+
++
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.
Maybe you could try the cookie method in this comment.
About the enter on url, it should be handled by the following part.
// Attach the event click for all links in the page $("a").bind("click", function() { validNavigation = true; });where to use prompt box and ajax call ?
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; } } }Sorry, can you elaborate more?
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
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
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
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
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
Mmh the code got deleted. Here it is again without the brackets
*fixed the syntax highlight by ykyuen
Your approach should be helpful to anyone who needs to work with ajax. Thanks for your code. =D
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.
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
$("a#tab-id]").bind("click", function() { validNavigation = true; });where tab-id is the id of the <a> element. i.e.
Hi
Please upload the Update and final javascript..
Thanks a lots….
The Update @ 2012-02-19 is already the latest one.
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…
Unfortunately the window.onbeforeunload in Chrome needs a returned string and seems that it must display a 2 options alert box (Stay or Leave).
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?
For browser back button, you can refer to this comment.
There is no way to detect the browser reload button.
Thanks for the quick reply..:)
you are welcome. =)
Thank you for your code!
Very cool sorce!!
thanks for your comment. =)
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?
Reference site: http://stackoverflow.com/questions/11257234/window-onbeforeunload-event-not-working-in-samsung-tab
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.
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.
you want the popup message appear on closing the new window or main window?
on main window..
i think u need to reset the validNavigation to false after the new window is opened. maybe add it at the end of ShowDocument.
function ShowDocument(url) { ... validNavigation = false; }does it solve the problem?
yes it solved my problem by resetting the validNavigation to false..
great. =)
This works perfectly.
function ShowDocument(url) { ... var mywindow = window.open(url, \”docwindow1\”, \”menubar=no,scrollbars =yes,top=0,left=0\”); mywindow.onunload = function(e) { validNavigation = false;}; }thanks for your code. =)
TT I hava a problerm
$(window).bind('beforeunload', goodbye); // Attach the event keypress to exclude the F5 refresh $('document').bind('keypress', function(e) { if (e.keyCode == 116) { validNavigation = true; alert("f5"); } }); // Attach the event click for all links in the page $("a").bind("click", function() { validNavigation = true; alert("a"); }); // Attach the event submit for all forms in the page $("form").bind("submit", function() { validNavigation = true; alert("form"); }); // Attach the event click for all inputs in the page $("input[type=submit]").bind("click", function() { validNavigation = true; alert("submit"); });only i can use this -> $(“a”).bind(“click”, function() .
f5, form, submit cant use TT
how can i solve?
for keypress: try using document without single quotes:
$(document).bind('keypress', function(e) { if (e.keyCode == 116) { validNavigation = true; alert("f5"); } });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..?
i think you can find some examples for detecting the browser back button @ StackOverflow – Detecting Back Button/Hash Change in URL
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.
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.
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..?
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”…
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.
How to handle the form submission through javascript and refresh events?
I meant browser meta refresh event
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.
Thanks for reply it worked
…below is code I was referring in my previous comment for refresing the page at a specific interval:
Great. good to know that u have solved the problem. =D
For those wanting to do ajax before unload you need to do a synchronous ajax call
Thx. =)
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?
You can customize it by editing this string.
But for some browsers, the leaving dialogue is a default msg which cannot be modified.
yes. In chrome they use their message. And we can’t give link in leave box right na?
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
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
Thanks for your suggestion. Gracias =D
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.
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.
Pingback: Handle Browser close event « Diwakar
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
You are welcome and thx for your comment. =D
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)?
you can use the window.onunload. for example, add the following line in the .js.
window.onunload = function(){ window.open('http://eureka.ykyuen.info'); };If you click Yes, the window.onunload will be triggered. The above code will open a new window showing this blog.
Hope this help. =)
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?
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?
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
Good to know that you have solved the problem. =D
Hi! How do you know if the user clicks on “accept” or “cancel” ?
You could add the implementation of the window.onunload event in the .js file.
window.onunload = function(){ alert('leave button is clicked'); };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?
Hello again,
This solved the isseu.
function ShowDocument(url) {
var mywindow = window.open(“http://www.google.nl”);
mywindow.onunload = function(e) { validNavigation = false;};
}
O no did not solve it just workt one time maybe i did not refresh page.
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. =)
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.
I have removed the url and email address. =)
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.
———————————————————————————-
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
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
———————————————————————————————–
It’s ok~ thanks again for your code~ =D
and i hv updated line 61.
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
————————————————————————
var validNavigation = false; function wireUpEvents() { var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; if (is_chrome) { var test = 1; window.onbeforeunload = function(){ setTimeout(function(){ test = 2; setInterval(function(){ if (test = 2) { var x = confirm("\nIf you pushed the (cross) X the Close-button.\nChoose OK\n\nIf you pushed a other browser navigation button\nChoose: Cancel.") if ( x == true) { window.location = "/session_end.html"; window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html"
;
}
else
{
}
}
},0);
},50);
return "If you pushed the (cross) X the Close-button..\nChoose (Stay on this page)\nChoose (OK)\nChoose (Leave this page)\nChoose (OK)\n\nAIf you pushed a other browser navigation button\nChoose: (Leave this page)";
}
}
createCookie('rescookie','restcookie',0)
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
if (readCookie('welkom9278') !== 'gegroet9278')
{
var is_fire = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if (is_fire) {
/*alert('oops..seems like a pop-up blocker is enabled. Please disable');*/
window.onbeforeunload = function(){ var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
if (x) {
window.open("http://www.terraverdedesign.nl/session_end.html"
;
return false;
}
else {
}
}
}
createCookie('welkom9278','gegroet9278',0)
setInterval(function eraseCookie(welkom9278) {
createCookie('welkom9278',"",-1);
},200);
}
if (readCookie('welkom9268') !== 'gegroet9268')
{
var is_msie = navigator.userAgent.toLowerCase().indexOf('msie') > -1;
if (is_msie) {
/*alert('oops..seems like a pop-up blocker is enabled. Please disable');*/
window.onbeforeunload = function(){ var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
if (x) {
window.open("http://www.terraverdedesign.nl/session_end.html"
;
window.onbeforeunload= x
return false;
}
else
{
return false;
}
}
}
createCookie('welkom9268','gegroet9268',0)
setInterval(function eraseCookie(welkom9268) {
createCookie('welkom9268',"",-1);
},200);
}
if (is_safari) {
var tesx = 3;
window.onbeforeunload = function(){
setTimeout(function(){
tesx = 4;
setInterval(function(){
if (tesx = 4) {
var x = confirm("\nIf you pushed the (cross) X the Close-button.\nChoose OK\n\nIf you pushed a other browser navigation button\nChoose: Cancel.")
if ( x == true)
{
window.location = "/session_end.html";
window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html"
;
}
else
{
}
}
},0);
},50);
return "If you pushed the (cross) X the Close-button..\nChoose (Stay on this page)\nChoose (OK)\nChoose (Leave this page)\nChoose (OK)\n\nAIf you pushed a other browser navigation button\nChoose: (Leave this page)";
}}
$("a").bind("click", function() {
validNavigation = true;
window.onbeforeunload= null;
window.onunload= null;
});
$('a').click(function(){
validNavigation = true;
window.onbeforeunload= null;
window.onunload= null;
});
$(window).bind('click', function(event) {
if(event.target.href) $(window).unbind('beforeunload');
validNavigation = true;
window.onbeforeunload = null;
window.onunload = null;
});
document.onkeydown = function disableKeys() {
if( typeof event != 'undefined' ) {
if(event.keyCode == 116) {
validNavigation = true;
event.keyCode = 0;
return false;
}
}
};
$("form").bind("submit", function() {
validNavigation = true;
});
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
$(document).ready(function() {
wireUpEvents();
});
Thanks for your effort. you could keep posting and i will summarize it on this blog post once the code is finalized. =D
Hey D,
I will spear you the summerize part and post once the code is finalized. Thanks this blog is realy helpfull.
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?
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.
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.
thanks for your clarification~ i didn’t know you have solved the 2nd question. =P
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.
//----------------------------------------------------------------------------------------- var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1; if (is_opera) { awt = window.setTimeout(function eraseCookie(welkom9968) {createCookie('welkom9968','gegroet9968',0) },1000); // Add Event function xwin = new Object(); if (readCookie('welkom9988') !== 'gegroet9988') { var xwin = window.open('/bloemenspeciaalzaak-terraverdedesign.html', 'SessionStart') , int = window.setTimeout(function () { if (xwin.closed !== true) { alert('\nPlease Klik on(OK) and then on (Allow Pop-up) Below in the right corner of your display.\n\nOpera needs a extra tab to see if you leave this site.\n\nClose both tabs when you leave this website, bedankt.\n\nThanks for your visit.'); } },50); } createCookie('welkom9988','gegroet9988',0) kk = window.setInterval(function () { if (window.name !== 'SessionStart') { window.location.reload(); if (typeof xwin.closed == 'undefined') { alert('\nPlease klik (OK)/n/nThe the session will be ending.') var xwun = window.location.href = '/session_end.html'; } }},2000); if ( $("input[type=submit]").bind("click", function(event) { if(event.target.href) { //alert ('link2'); //To not popup the warning message } else { // alert ('somthing else like a button2'); int = window.setTimeout(function eraseCookie(welkom9968) { createCookie('welkom9968',"",-1); },0); }})); if ( $(window).bind('click', function(event) { if(event.target.href){ //alert ('link'); //To not popup the warning message int = window.setTimeout(function eraseCookie(welkom9968) { createCookie('welkom9968',"",-1); },0); //To not popup the warning message } else { }})); } //------------------------------------------------------------------------------------------------------------------------------------------------------ // /session_end.html //------------------------------------------------------------------------------------------------------------------------------------------------------ //Your cookie session is ending. //Page closes automaticly. // //<?php //if(isset($_SERVER['HTTP_COOKIE'])){ // //$cookies = explode(';', $_SERVER['HTTP_COOKIE']); // foreach($cookies as $cookie){ // $parts = explode('=', $cookie); // $name = trim($parts[0]); // setcookie($name,'', time()-1000); // setcookie($name,'', time()-1000,'/'); // } //} //session_unset(); //session_destroy(); //?> // //<form name="redirect" class="serb"> //<p class="clountdown">Deze webpagina wordt gesloten in:</p> //<form> //<input name="redirect2" type="text" class="countdown"> //<p class="clountdown">Seconden</p> //</form> // // //<script language="javascript" type="text/javascript"> //var countdownfrom=3 //var currentsecond=document.redirect.redirect2.value=countdownfrom+1 //function countredirect(){ //if (currentsecond!=1){ //currentsecond-=1 //document.redirect.redirect2.value=currentsecond //} //else{ //var objWindow = window.open(location.href, "_self"); objWindow.close(); //window.name = 'SessionEnd' //window.open('/session_end.html','SessionEnd',''); //SessionEnd.close(); //self.close(); //window.open('','_self',''); //window.close(); //win.close(); //return //} //setTimeout("countredirect()",1000) //} // //countredirect() //<//script> //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?
You can put all the inline code into a .js file and then include it inside the <head>.
Thanks for the reply.
But, this is for each page which means we need to include in each . Right?
yes, you need to include it on each page.
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…..
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
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.
As u read in the code, it tries to disable the message box for specific action by setting validNavigation to true. e.x.
// Attach the event click for all links in the page $("a").bind("click", function() { validNavigation = true; });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.
// Attach the event click for all links with class "no-message-box" $(".no-message-box").bind("click", function() { validNavigation = true; });So any hyperlink with class “no-message-box” will not trigger the message box.
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……
So just add the class to the child menu items in order to disable the alert message box.
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
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.
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
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.
window.onbeforeunload = function (evt) { var message = 'Are you sure you want to leave?'; if (typeof evt == 'undefined') { evt = window.event; } if (evt) { evt.returnValue = message; } return message; }Thanks for the code. =)
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.
You can prepare the form in another url and open it up in a new browser window. You can refer to this comment.
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
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:
var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1; if (is_opera) { awt = window.setTimeout(function eraseCookie(welkom9968) {createCookie('welkom9968','gegroet9968',0) },1000); // Add Event function xwin = new Object(); if (readCookie('welkom9988') !== 'gegroet9988') { var xwin = window.open('/bloemenspeciaalzaak-terraverdedesign.html', 'SessionStart') // url the start page off your sie: , int = window.setTimeout(function () { if (xwin.closed !== true) { alert('\nPlease Klik on(OK) and then on (Allow Pop-up) Below in the right corner of your display.\n\nOpera needs a extra tab to see if you leave this site.\n\nClose both tabs when you leave this website, bedankt.\n\nThanks for your visit.'); } },50); } createCookie('welkom9988','gegroet9988',0) kk = window.setInterval(function () { if (window.name !== 'SessionStart') { window.location.reload(); if (typeof xwin.closed == 'undefined') { alert('\nPlease klik (OK)/n/nThe the session will be ending.') var xwun = window.location.href = '/session_end.html'; // URL you end your session add. or some function } }},2000); if ( $("input[type=submit]").bind("click", function(event) { if(event.target.href) { //alert ('link2'); //To not popup the warning message } else { // alert ('somthing else like a button2'); int = window.setTimeout(function eraseCookie(welkom9968) { createCookie('welkom9968',"",-1); },0); }})); if ( $(window).bind('click', function(event) { if(event.target.href){ //alert ('link'); //To not popup the warning message int = window.setTimeout(function eraseCookie(welkom9968) { createCookie('welkom9968',"",-1); },0); //To not popup the warning message } else { }})); }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
" = is wrong it just needs to be: “
Pingback: How to Destroy Session When users close the browser tab in php | yuvrajingale
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?
Thit u use this?
function okEvent(){ validNavigation = true; } $(':button').click(okEvent); $("form").bind("submit", okEvent ); $("a").bind("click", function() { validNavigation = true; window.onbeforeunload= null; window.onunload= null; }); $('a').click(function(){ validNavigation = true; window.onbeforeunload= null; window.onunload= null; }); $(window).bind('click', function(event) { if(event.target.href) $(window).unbind('beforeunload'); validNavigation = true; window.onbeforeunload = null; window.onunload = null; }); document.onkeydown = function disableKeys() { if( typeof event != 'undefined' ) { if(event.keyCode == 116) { validNavigation = true; event.keyCode = 0; //return false; } } }; $("form").bind("submit", function() { validNavigation = true; }); $("input[type=submit]").bind("click", function() { validNavigation = true; });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.
var validNavigation = false; function wireUpEvents() { //set dont_confirm_leave to 1 when you want the user to be able to leave without confirmation var dont_confirm_leave = 0; function closeInChrome(e) { if (!validNavigation) { if (dont_confirm_leave != 1) { window.open('http://www.google.com', 'google','width=800,height=600,status=0,toolbar=0'); return null; } } } var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; if (is_chrome) { window.onbeforeunload = closeInChrome } else{ window.onbeforeunload = function () { if (!validNavigation) { validNavigation = false; window.open('http://www.google.com', 'google','width=800,height=600,status=0,toolbar=0'); } } } $('a').click(function () { window.onunload = null; window.onbeforeunload = null; }); document.onkeydown = function disableKeys() { if (typeof event != 'undefined') { if ( event.keyCode == 112 || event.keyCode == 116) { validNavigation = true; event.keyCode = 0; return false; //return false if u want to disable refresh } } }; /* // Attach the event keypress to exclude the F5 refresh $('html').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; }); $("input[type=button]").bind("click", function () { validNavigation = true; }); $(".active-menu").bind("click", function() { validNavigation = true; }); } // Wire up the events as soon as the DOM tree is ready $(document).ready(function () { wireUpEvents(); });Hi Ykyuen,
thanks for the code works well. I had to add one thing to handle navigation triggered by window.location.href.
(JEROEN says) Hello I use this code:
var validNavigation = false; function wireUpEvents() { var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1; var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; if (is_chrome) { var test = 1; window.onbeforeunload = function(){ setTimeout(function(){ test = 2; setInterval(function(){ if (test = 2) { var x = confirm("\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct: annuleren.") if ( x == true) { window.location = "/session_end.html"; window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html"
;
}
else
{
}
}
},0);
},50);
return "Als je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan (Op deze pagina blijven)\nKies dan (OK)\nKies dan (Deze pagina verlaten)\nKies dan (OK)\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct: (Deze pagina verlaten)";
}
}
createCookie('rescookie','restcookie',0)
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
if (readCookie('welkom9278') !== 'gegroet9278')
{
var is_fire = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if (is_fire) {
window.onbeforeunload = function(){ var x=window.confirm("Oeps.. het lijkt erop dat er een pop-up blocker aan staat.\n\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\nKies (stay on this page)!\nKies dan in de pop-up blokker (always allow popups for this site)\nKies nogmaals OK\n\n De pop-up pagina sluit vanzelf binnen 5 seconden\n\nVoor de pagina die dan nog niet is afgesloten.\nSluit dan de pagina nogmaals. en kies dan Annuleren\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct; Annuleren. ")
if (x) {
window.open("http://www.terraverdedesign.nl/session_end.html"
;
return false;
}
else {
}
}
}
createCookie('welkom9278','gegroet9278',0)
setInterval(function eraseCookie(welkom9278) {
createCookie('welkom9278',"",-1);
},200);
}
if (readCookie('welkom9268') !== 'gegroet9268')
{
var is_msie = navigator.userAgent.toLowerCase().indexOf('msie') > -1;
if (is_msie) {
window.onbeforeunload = function(){ var x=window.confirm("Oeps.. het lijkt erop dat er een pop-up blocker aan staat.\n\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\nKies (stay on this page)!\nKies dan in de pop-up blokker (always allow popups for this site)\nKies nogmaals OK\n\n De pop-up pagina sluit vanzelf binnen 5 seconden\n\nVoor de pagina die dan nog niet is afgesloten.\nSluit dan de pagina nogmaals. en kies dan Annuleren\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct; Annuleren. ")
if (x) {
window.open("http://www.terraverdedesign.nl/session_end.html"
;
window.onbeforeunload= x
return false;
}
else
{
return false;
}
}
}
createCookie('welkom9268','gegroet9268',0)
setInterval(function eraseCookie(welkom9268) {
createCookie('welkom9268',"",-1);
},200);
}
if (is_safari) {
var tesx = 3;
window.onbeforeunload = function(){
setTimeout(function(){
tesx = 4;
setInterval(function(){
if (tesx = 4) {
var x = confirm("\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct: annuleren.")
if ( x == true)
{
window.location = "/session_end.html";
window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html"
;
}
else
{
}
}
},0);
},50);
return "Als je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan (Op deze pagina blijven)\nKies dan (OK)\nKies dan (Deze pagina verlaten)\nKies dan (OK)\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct: (Deze pagina verlaten)";
}}
if (is_opera) {
awt = window.setTimeout(function eraseCookie(welkom9968)
{createCookie('welkom9968','gegroet9968',0)
},1000);
xwin = new Object();
if (readCookie('welkom9988') !== 'gegroet9988')
{
var xwin = window.open('/bloemenspeciaalzaak-terraverdedesign.html', 'SessionStart')
, int = window.setTimeout(function () {
if (xwin.closed !== true) {
alert('\nKlikt u A.U.B op (OK) en daarna op (Pop-up toestaan) rechtsonder in de hoek van uw scherm.\n\nOpera heeft een extra tabblad nodig om te kunnen zien wanneer u de website verlaat.\n\nSluit beide tabbladen pas bij het verlaten van deze website, bedankt.\n\nBedankt voor uw bezoek.');
}
},50);
}
createCookie('welkom9988','gegroet9988',0)
kk = window.setInterval(function () {
if (window.name !== 'SessionStart')
{
window.location.reload();
if (typeof xwin.closed == 'undefined') {
alert('\nKlikt u A.U.B op (OK)/n/nDan wordt de session beeindigd bedankt.')
var xwun = window.location.href = '/session_end.html';
}
}},2000);
if ( $("input[type=submit]").bind("click", function(event) {
if(event.target.href) {
} else {
int = window.setTimeout(function eraseCookie(welkom9968) {
createCookie('welkom9968',"",-1);
},0);
}}));
if ( $(window).bind('click', function(event) {
if(event.target.href){
int = window.setTimeout(function eraseCookie(welkom9968) {
createCookie('welkom9968',"",-1);
},0);
} else {
}}));
}
function okEvent(){
validNavigation = true;
}
$(':button').click(okEvent);
$("form").bind("submit", okEvent );
$("a").bind("click", function() {
validNavigation = true;
window.onbeforeunload= null;
window.onunload= null;
});
$('a').click(function(){
validNavigation = true;
window.onbeforeunload= null;
window.onunload= null;
});
$(window).bind('click', function(event) {
if(event.target.href) $(window).unbind('beforeunload');
validNavigation = true;
window.onbeforeunload = null;
window.onunload = null;
});
document.onkeydown = function disableKeys() {
if( typeof event != 'undefined' ) {
if(event.keyCode == 116) {
validNavigation = true;
event.keyCode = 0;
}
}
};
$("form").bind("submit", function() {
validNavigation = true;
});
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
$(document).ready(function() {
wireUpEvents();
});
Opps i see i posted the dutch version here is the english version!”
var validNavigation = false; function wireUpEvents() { var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1; var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; if (is_chrome) { var test = 1; window.onbeforeunload = function(){ setTimeout(function(){ test = 2; setInterval(function(){ if (test = 2) { var x = confirm("\nIf you pushed the (cross) X the Close-button.\nChoose OK\n\nIf you pushed a other browser navigation button\nChoose: Cancel.") if ( x == true) { window.location = "/session_end.html"; window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html"
;
}
else
{
}
}
},0);
},50);
return "If you pushed the (cross) X the Close-button..\nChoose (Stay on this page)\nChoose (OK)\nChoose (Leave this page)\nChoose (OK)\n\nAIf you pushed a other browser navigation button\nChoose: (Leave this page)";
}
}
createCookie('rescookie','restcookie',0)
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
if (readCookie('welkom9278') !== 'gegroet9278')
{
var is_fire = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if (is_fire) {
window.onbeforeunload = function(){ var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
if (x) {
window.open("http://www.terraverdedesign.nl/session_end.html"
;
return false;
}
else {
}
}
}
createCookie('welkom9278','gegroet9278',0)
setInterval(function eraseCookie(welkom9278) {
createCookie('welkom9278',"",-1);
},200);
}
if (readCookie('welkom9268') !== 'gegroet9268')
{
var is_msie = navigator.userAgent.toLowerCase().indexOf('msie') > -1;
if (is_msie) {
window.onbeforeunload = function(){ var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
if (x) {
window.open("http://www.terraverdedesign.nl/session_end.html"
;
window.onbeforeunload= x
return false;
}
else
{
return false;
}
}
}
createCookie('welkom9268','gegroet9268',0)
setInterval(function eraseCookie(welkom9268) {
createCookie('welkom9268',"",-1);
},200);
}
if (is_safari) {
var tesx = 3;
window.onbeforeunload = function(){
setTimeout(function(){
tesx = 4;
setInterval(function(){
if (tesx = 4) {
var x = confirm("\nIf you pushed the (cross) X the Close-button.\nChoose OK\n\nIf you pushed a other browser navigation button\nChoose: Cancel.")
if ( x == true)
{
window.location = "/session_end.html";
window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html"
;
}
else
{
}
}
},0);
},50);
return "If you pushed the (cross) X the Close-button..\nChoose (Stay on this page)\nChoose (OK)\nChoose (Leave this page)\nChoose (OK)\n\nAIf you pushed a other browser navigation button\nChoose: (Leave this page)";
}}
if (is_opera) {
awt = window.setTimeout(function eraseCookie(welkom9968)
{createCookie('welkom9968','gegroet9968',0)
},1000);
xwin = new Object();
if (readCookie('welkom9988') !== 'gegroet9988')
{
var xwin = window.open('/bloemenspeciaalzaak-terraverdedesign.html', 'SessionStart')
, int = window.setTimeout(function () {
if (xwin.closed !== true) {
alert('\nPlease Klik on(OK) and then on (Allow Pop-up) Below in the right corner of your display.\n\nOpera needs a extra tab to see if you leave this site.\n\nClose both tabs when you leave this website, Thanks.\n\nThanks for your visit.');
}
},50);
}
createCookie('welkom9988','gegroet9988',0)
kk = window.setInterval(function () {
if (window.name !== 'SessionStart')
{
window.location.reload();
if (typeof xwin.closed == 'undefined') {
alert('\nPlease klik (OK)/n/nThe the session will be ending.')
var xwun = window.location.href = '/session_end.html';
}
}},2000);
if ( $("input[type=submit]").bind("click", function(event) {
if(event.target.href) {
} else {
int = window.setTimeout(function eraseCookie(welkom9968) {
createCookie('welkom9968',"",-1);
},0);
}}));
if ( $(window).bind('click', function(event) {
if(event.target.href){
int = window.setTimeout(function eraseCookie(welkom9968) {
createCookie('welkom9968',"",-1);
},0);
} else {
}}));
}
//------------------------------------------------------------------------------------------------------------------------------------------------------
function okEvent(){
validNavigation = true;
}
$(':button').click(okEvent);
$("form").bind("submit", okEvent );
$("a").bind("click", function() {
validNavigation = true;
window.onbeforeunload= null;
window.onunload= null;
});
$('a').click(function(){
validNavigation = true;
window.onbeforeunload= null;
window.onunload= null;
});
$(window).bind('click', function(event) {
if(event.target.href) $(window).unbind('beforeunload');
validNavigation = true;
window.onbeforeunload = null;
window.onunload = null;
});
document.onkeydown = function disableKeys() {
if( typeof event != 'undefined' ) {
if(event.keyCode == 116) {
validNavigation = true;
event.keyCode = 0;
}
}
};
$("form").bind("submit", function() {
validNavigation = true;
});
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
$(document).ready(function() {
wireUpEvents();
});
This version works in Opera, Safari, Firefox, Internet explorer and Chroom
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:
function goodbye(e) { if (!validNavigation) { var e = e || window.event; // For IE and Firefox if (e) { e.returnValue = ''; location.href = "logout.php"; return e.returnValue; } } } window.onbeforeunload=goodbye;here section is expired in IE and FF.
Please suggest me how can get this in chrome browser.
I guess the confirm messages of chrome browser is the return messages. how about doing a redirect before the return?
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 location.href = "logout.php"; // return leave_message; } } }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?
You can schedule a function using setTimeout() and set validNavigation = true.
sth like
setTimeout(validateRegularUsers, 60000); function validateRegularUsers() { validNavigation = true; }Reference: jQuery & Javascript – Schedule a Function call by setTimeout()
can anyone reply,what to do when i want to delete a file on window/tab close? i am using ajax for this
$.ajax({ type: "POST", data:"file="+ , url:"delete_csv.php"; dataType:"json", success: function(response) { alert("Delete"); } });where to put my ajax code in this case?
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.
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.
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.
Hi Friend..
Good Script..
I am Using below code…
————————————————————————–
var validNavigation = false; function endSession() { // Browser or broswer tab is closed // Do sth here ... alert("bye"); } function wireUpEvents() { 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(); });——————————————————————————
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
is your input type = “button”? if yes, you could bypass it by adding
$("input[type=button]").bind("click", function() { validNavigation = true; });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’)
Thanks for pointing out the mistake. i have updated the post. =)
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?
Hi Mark, Jerome has made the script works in opera. you could refer to this comment. hope it could help.
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?
you can add an id on those anchor and exclude them by
// Attach the event click for all links in the page $("a#your-id").bind("click", function() { validNavigation = false; });Does it work?
Great post. You should add it to Github
Yes~ will do later. thanks for your suggestion. =D