Last updated on February 9th, 2022 at 10:45 am
Javascript Detect browser close event and alert message
This script will help you to detect browser or tab close event and alert some messages. Even this script will be useful to call some Ajax functions which terminate connection to Database or something related.
Tested on latest version of Chrome and Internet Explorer 11.0 and Microsoft Edge. [Last validated on Sept 24th 2016]
Tested on latest version of Chrome, Firefox, Safari [Last validated on Feb 9th 2022]
If you would like to run some functions before closing the browser, check this tutorial on Calling a function before leaving a website using Javascript.
You can try this code, it basically calls onbeforeunload property of the WindowEventHandlers
<body onbeforeunload="return check()">
<script type="text/javascript">
window.onbeforeunload = check;
function check()
{
return "Are you sure you want to exit this page?";
//or put whatever function you need to call when a user closes the web //browser.
}
</script>
<body>
Body of the page goes here.
</body>
Note: In the demo you must type something in the input field or click somewhere in the page to activate the listener. Simply opening the demo page and closing it may not trigger a confirmation pop up
it is not working for google chrome!!
Use this in chrome
This should work with Chrome/IE/Mozilla
i want to redirect it to logout.so what should i use in function { };
Hi Prasenjit, Thanks for the comment.
For that you need to add after the alert command something like
Where logout.php is your logout script.Hope your script works as expected.
not working…
Remove all the existing functions for unload event and add this, it will work on all browsers like Firfox, Chrome and IE.
thnks,its working…
Hii
It is working in all the cases in window load and close I want want it only in close case what should I do plz suggest 🙂
it identifies all cases where window is unloading: reload, window.location change etc.
what about only browser exit event?
Thanks a lot,
this worked for me also. Keep up the good work.
Greetings from Holland
is there a way that it will delete my session in the database?
like this (no working example)
window.onbeforeunload = function (my_event) {
if (typeof my_event == ‘undefined’) {
my_event = window.event;
}
if (my_event) {
newWindow=window.open(‘http://www.url.com/logout.php?sesjion=’)
newWindow.focus();
my_event.returnValue = alert;
}
return alert;
}
}
thanks in advance.
kindest regards Menno
if (my_event) {
newWindow=window.open(‘http://www.url.com/logout.php?sesjion= php string session end php’)
newWindow.focus();
my_event.returnValue = message;
the link will be:
http://www.url.com/logout.php?sesjion=e4b9f06fe57c6e9b98b60e4463525092
it needs to take the session to the logout.php page in the URL bar.
then destroy it.
Logged in member –> closes browser –> open the page
http://www.url.com/logout.php?sesjion=e4b9f06fe57c6e9b98b60e4463525092
session_destroy
update DB set session to ’empty’.
on manual this works 🙂 now i need the script to do it.
Thanks in advance
Menno
Please check my previous comment. Replace the URL in that with anything according to your requirement. Add a auto close window script which will close that window automatically once the logout session is empty.
Hi Menno,
Thank you very much for your query. Yes there is a way to do that. As mentioned in the script inside the myUnloadEvent() function you can add your URL that will delete the session from your db, You can do a simple approach like this.
Else use the script you have pasted. If that doesn’t work go ahead with mine 🙂
Regards
Admin[Mistonline.in]
super answer i got relified thank you
Hello,
the script is great!
But unfortunately when we are on a web application including main_menu frame, each time we go from one menu to another we get the alert, or even when we click on a link.
Is there any way to only detect browser closing and not unload?
Thanks.
Manickam
Its possible in chrome detect when browser or tab closed but NOT showing a message, directly open a popup, I dont wanna show a message, it is possible?
Please find my answer to prasenjit query. You can remove the alert function and use window.open() instead.
I dont want the message to be given to user if the browser gets refreshed..i need a notification only when the user clicks on (X) to close the browser..please help
Hi Vikas,
For that you can use Cookies. If you can wait for some more time my next post will be based on that 🙂
Regards
Admin
Sir, I want to set my database value from 1 to 0 when browser is closed….Is there any way to do this..please assist me..Thank you
You can use jquery for that. Javascript has onbeforeunload() but at times it will not be compatible with some browser.
Jquery code should looks something like this
Hope this will give you some hint on how to do it 🙂
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.
var validNavigation = false;
var test=false;
function wireUpEvents() {
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= (function(event){
if(!validNavigation){
return goodbye(event);
}
})
// Attach the event keypress to exclude the F5 refresh
$(document).bind(‘keydown’, function(e) {
getKeyCode(e);
if (keyCd == 116){
validNavigation = true;
}
if (altKy && (keyCd == 18 || keyCd == 115)) {
validNavigation = true;
}
if (keyCd == 13) {
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;
});
}
function getMouseButton(event) {
if (IE == true) {
mouseBtn = event.button;
}
if (Netscape == true) {
if (event.which == null)
mouseBtn = event.button;
else
mouseBtn = event.which;
}
}
function getKeyCode(event) {
if (IE == true) {
keyCd = event.keyCode;
altKy = event.altKey;
ctlKy = event.ctlKey;
shiftKy = event.shiftKey;
}
if (Netscape == true) {
if (event.which == null)
keyCd = event.keyCode;
else
keyCd = event.which;
altKy = event.altKey;
ctlKy = event.ctrlKey;
shiftKy = event.shiftKey;
}
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
var keyCd, altKy, mouseBtn, ctlKy, shiftKy;
Browser = navigator.appName
Net = Browser.indexOf(“Netscape”)
Micro = Browser.indexOf(“Microsoft”)
Netscape = false
IE = false
if (Net >= 0) {
window.captureEvents(Event.MOUSEDOWN)
Netscape = true
}
if (Micro >= 0) {
IE = true
}
wireUpEvents();
});
Hello Rakesh, Thanks a lot for your comment.
Please refer http://www.w3schools.com/tags/ref_eventattributes.asp, and kindly note that only window object has a load event. So as far as i know you will not be able to trigger a function only when you refresh your webpage.
The script i have given below is the closest one i can recommend for you. This will work when you close, refresh or type a new address and click enter on the address bar.