This was the question I was asking myself when I Β had to write a piece of code which needed to respond differently on browser close and on browser refresh. To my worst nightmare i found this issue seemed to trouble a lot a people, i went through lots of forums and blogs which gave multiple solutions some even advising to forget the requirement, as it seemed near impossible to detect the difference between a browser close and refresh.
I think i have stumbled on a snippet of code which will detect if the page was refreshed or closed. I had tested this code on windows (IE 7,8,9 – Chrome – Firefox – Safari – Opera) and mac (Safari 4,5 – Firefox – Chrome).
This is a experimental code which i would like you to use and review it. Do let me know your comments.
On request i am including the 2 sample test files which i used to test on my machine. Run the file test.html from the zip file. Which on close / on refresh of the window will open a popup and once the new popup comes check your browser’s console log.
You will find the parent window close / refresh status message on the console after a 2 second delay. This delay is for the browser to complete the DOM manipulation i.e. close or refresh before we do the check. Please click on the sample code link to download the sample code.
Sample Code
Update: 27/03/2017::
New Sample Code Which Works π
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* ::How this works:: 1. Checking if an invalid property exist in an object 2. If parent window exist the return will be 'undefined' 3. If parent window does not exist, an exception will be raised which we will catch 4. This exception will tell us that the parent no loger exist thus parent got closed. Note: this check is run with a 1 sec delay to make sure the window object gets closed properly. */ function detectRefresh(){ try { if(window.opener.title == undefined){ isRefresh = true; document.write('Window was refreshed!'); } } catch(err) { isRefresh = false; document.write('Window was closed!'); } } |
This is an interesting solution. I have been hunting for the same for some time now !! thanks a ton !!
You are welcome Sreejith. Do let me know your comments thought π
Hi! π it’s an interesting solution! How can I implement it on my html page?
Can you help me on how to call that function?
hello stimart , on the sample html page you need to use the ‘onbeforeunload’ event on body tag to do a ‘window.open’ of another html file which should contain the detect refresh code. you can use the settimeout method in javascript to call the detectrefresh method in 1sec interval after page is ready. once the poppup is triggered check your console log for window refresh or close message.
Excellent solution, this works perfect. Saved my day π
Hi Swaroop, I am glad that the solution worked for you.
Cheers.
Looks like this solution is not working in chrome version 22.
Thank You Swaroop for your comments. I am looking into the code. I shall update a solution as soon as i can find one.
Cheers
Hello Swaroop,
As promised I did check the code in detail and i was able to run the code on Chrome version 22 without any glitches. I request you to download my sample code from the url at the end of the comment and check once again. Please do let me know if you need more help.
Happy Coding.
Cheers.
http://cdn.anandkanatt.com/wp-content/uploads/2012/08/samplecode.zip
clever trick, but this only works if the client isn’t blocking popups, right?
Hi Zeke,
Yes, This works when the popup blocker is not blocking the popups. Though i have not checked in the popup blocking case, would be great if you could let me know your findings.
Tnx a lot for this post. I am designing an online exam where I used Jquery to load next questions. Everythn is working fine including my countdown timer. But once a user refreshes the page, both the countdown timer and the question starts afresh. So I want to detect if the user refresh the page so that I can penalize him by kicking him out of the test. I just want a php code that can detect that then I’ll complete the rest of the code………all the same, l’ll give ur code a try. Tnx dude……..pls kindly mail me on my email above, u can as well follow me on twitter @Abdullmeela, on fzbk: Abdull Meela…….I really need u as my mentor. Pls help. Tnx
I am glad that i was able to help you with my code.
Srry, u can also help me with javascrpt code (preferably) for this. Tnx.
Not working on my side. It keeps showing in the log, “Window was closed! ”
Please help.
Can you give me more details John ?
Hello Anand,
The sample looks impressive, but what if I want to stop closing page. My requirement was if User click on ‘X’ (Close) I want to show User Notification about the unsaved changes.. Refresh is still okay for me..
I tried to modified your code a bit.. but looks like theres no way you can have Window.Opener == NULL in another window when your parent window is alive and opened..
Do you have any idea about how that can be achieved. ?
This can be done by simply putting a ‘onbeforeunload’ event handler with a simple text asking user to save changes before exiting. Like ‘Are you sure you want to exit ?’ . with this message as return value, JS will show a prompt to user to take a decision. you can dynamically attach an event handler when any unfinished business is there on the page.
Add below code in view file
window.onbeforeunload = function () {
};
Write your user notification code inside window.onbeforeunload
Hi,
I want to detect the browser refresh event, but do not want to open any new html. is there a way to do that?
Hi Shravanthy,
Sorry but I do not have a different solution at this time.
Hi,
It’s not working on my side too (Same as John). It keeps showing in the log, βWindow was closed!
Its on Chrome Version 43.0.2357.124 m.
I used a similar solution, I check the window.parent.closed. But my exact problem is to detect back of browser and refresh. Do you know a way to differentiate between back and refresh pressed? As in both cases parent window is not closed!
Hi Shrin,
Please find the working code in the following url:
https://www.anandkanatt.com/wp-content/uploads/2012/08/samplecode.zip
I have tested the code on
1: Chrome 44.0.2403.155 m (64-bit)
2: Firefox 39.0.3
hi can you send me the proper sample code of html page ?
Hi Vishal,
Please find the working code in the following url:
https://www.anandkanatt.com/wp-content/uploads/2012/08/samplecode.zip
I have tested the code on
1: Chrome 44.0.2403.155 m (64-bit)
2: Firefox 39.0.3
Hi, I have tested the code on Chrome Version 48.0.2564.116, it always shows the alert message of catch block, i mean window was closed. i have changed console.log to alert.
I couldn’t get this working in Chrome v49.0.2623.87 (64-bit). I had both test.html and test2.html running on python SimpleHTTPServer in 2 different tabs. I refreshed test2.html numerous times but everytime it said “Window was closed!”. I never got “Window was refreshed!” in the console log.
Ideally, I want to get this working in all browsers. Please give me any relevant pointers if you have.
Hi,
It is working fine when browser is refreshed on using of onbeforeunload but here the problem is when i used to close the browser isrefresh giving true value….
it is not working in latest versions. I have tested with chrome 56.X
Hi Vijay,
Thank you for the message.
I have made some changes to the code and updated the article now.
Check and do let me know if works for you.
Thanks
Anand
Hi Anand,
I tried to use your solution but it was returning the window.opener as null. I have searched on that a bit and everywhere it says that the site (which has the window.opener code) should have been opened by some other site.
In my scenario I have page which is openedon login and I would like to determine if that page (logged in page) is going to be closed or refreshed. I tried using window.opener inside onbeforeunload event handler but was getting null returned for window.opener. Can you please help me with this? Can I use your solution in my scenario?
I am using Chrome 56.X
Thanks
Please check my reply to jifei on how it works.
cheers.
Hi,
Anand,Itβs not working on my side,my browser is chrome -version 56.0.2924.87 (64-bit)γ
i try to run this code , it step in to ” catch(err){}” when i try to get the value of window.opener.title.The code “if(window.opener.title== undefined)” is not work.
Besides,whether refresh or close the browser ,the value of window.opener.title is undefined.
Sorry for the late reply.
Yes this will work, just call test.html from your local web server or any other server.
Loading file directly from file system may not work.
e.g. http://localhost/test.html
This should load up test2.html when you refresh or close the test.html window
You will see a message on test2.html screen stating the test.html window was closed or open.
Let me know if it worked for you.
cheers.
Nice solution, the only problem is the requirement to open a popup, i wonder if it will also works for iframe? π
Hi,
Thanks.
I dont think this will work with an Iframe as the code uses parent/child window references.
This is working when we click refresh first and then close. But not working when close the browser (without doing a refresh). Please suggest.
Hi,
Just to check is you popup getting blocked ? Please check and confirm. Otherwise it should work.
hello
i am trying to detect event when user click on brawser close button.I use so many solution but not work.
Please help me to solve this problem.
Thank you
its not working
its not working worst
can i get sample code ?
if (window.opener) {
isRefresh = true;
document.write(‘Window was refreshed!’);
} else {
isRefresh = false;
document.write(‘Window was closed!’);
}