Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture the close event of popup window in JavaScript

I need to perform some action before a popup window(using window.open ) closes.

Something like will be good:

var new_window = window.open('some url') new_window.onBeforeUnload = function(){ my code} 

How can I achieve that?

like image 468
xiaohan2012 Avatar asked Feb 22 '12 02:02

xiaohan2012


People also ask

How do I close a popup in JavaScript?

self. close(); should do it. That should work from within the popup.

What a popup () method in JavaScript is?

In Javascript, popup boxes are used to display the message or notification to the user. There are three types of pop-up boxes in JavaScript namely Alert Box, Confirm Box and Prompt Box. Alert Box: It is used when a warning message is needed to be produced.

How do I close a popup in jQuery?

In this article, we will use jQuery Mobile Popup close() method to close an already opened popup. This method doesn't accept any parameter. Example: In the example below we will use Popup close() method to close the opened popup after 3000ms.


2 Answers

While the accepted answer is correct for same origins I found a solution for cross origin popups:

var win = window.open('http://www.google.com');  var timer = setInterval(function() {      if(win.closed) {         clearInterval(timer);         alert('closed');     } }, 1000); 

Source: atashbahar.com

For those considering using it.

Even Facebook is using this "hack" in their Javascript SDK.

You can verify this by having a look at their code. Just search for .closed in https://connect.facebook.net/en_US/sdk.js.

like image 145
Dustin Hoffner Avatar answered Oct 19 '22 04:10

Dustin Hoffner


Your example will work as long as the pop-up window url is in the same domain as the parent page, and you change the event to all lowercase:

var new_window = window.open('some url') new_window.onbeforeunload = function(){ /* my code */ } 
like image 27
glortho Avatar answered Oct 19 '22 04:10

glortho