5

How can I detect if a browser window was closed? I am opening a web page from my site in a new browser window.

I know people generally use unload event but the browser window that I am opening is a page which is not a part of my web site(e.g. www.google.com).

Is there any way to detect this?

Amey Khadatkar
  • 414
  • 3
  • 16
  • 1
    The dupe talks about the onload event, but it's applicable to any event in the other window - ie if it's on a different domain that you have no control of, no you can't detect it. – James Thorpe Oct 14 '15 at 13:26
  • 1
    Refer this: http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser – Rahul Tripathi Oct 14 '15 at 13:31
  • @JamesThorpe As seen in the accepted answer I need to won the domain. I don't own it in my scenario! – Amey Khadatkar Oct 14 '15 at 13:34
  • @RahulTripathi As u can see rahul i have already mentioned that i know about the events but that is not what i want! I don't own the page I am redirecting to! – Amey Khadatkar Oct 14 '15 at 13:35
  • Open the new window with a page from your own site containing an iframe with the other site inside it. Now you can use `unload` event as intended. – Simba Oct 14 '15 at 13:35
  • In short: you can't do it reliably. Best is implement a client-server "ping", and if the browser fails to send a ping after X times, assume it was closed. – Shadow The GPT Wizard Oct 14 '15 at 13:35
  • @Simba Go try putting google inside an iframe and see how far you get. – James Thorpe Oct 14 '15 at 13:37
  • Why is this a duplicate? The questions are different. Read carefully – Amey Khadatkar Oct 14 '15 at 13:37
  • @JamesThorpe Its not possible to open those pages in iframe. Its a security risk – Amey Khadatkar Oct 14 '15 at 13:38
  • @AmeyKhadatkar I know. Hence my comment. – James Thorpe Oct 14 '15 at 13:38
  • @AmeyKhadatkar To me it's a duplicate of the one I linked to as you're asking to handle the onunload event of a window from a domain you're not in control of. Unfortunately, the answer to your question _"Is there any way to detect this?"_ is "No". – James Thorpe Oct 14 '15 at 13:39
  • Another idea: from the parent window, you should be able to access the child window's DOM: If you have `var childWindow = window.open(....)` then you can do `var childDoc = childWindow.document;` etc. You could set up a timed event from the parent that checks regularly whether the child document exists. When it stops existing, then you know the window has been closed. (yes, this also could have cross-site security implications, so maybe won't be possible?) – Simba Oct 14 '15 at 13:40
  • @Simba _"so maybe won't be possible"_ You're right, it's not. – James Thorpe Oct 14 '15 at 13:41
  • You just gave an answer i.e. "No" then how come its a duplicate? The question u linked to doesn't help. – Amey Khadatkar Oct 14 '15 at 13:44

0 Answers0