Room of a pleinolijf

Ask yourself this: how do I want to be remembered ?

Capturing the Closing of a Window (‘X’) in JavaScript

1 Comment

I used this for an application I’m currently developing.

I have a questionnaire that users need to fill out by selecting answers to questions. These questionnaires appear in fullscreen popup windows (as requested by the client), which are opened by the main web site. On this main site, I have an aspx page that keeps track of the status of these questionnaires (it calculates the percentage completed by counting the received answers to the questions).

After a recent demo, the client asked to update the status page not only when a questionnaire is completed, but also whenever a user closed the popup window manually. I needed a workaround, as the “body onUnload” wasn’t good in my case, because it would be triggered every time the user navigates to another page in the test, and also with each postback of the ASP.NET questionnaires).

I found a decent solution in the following.

On the questionnaire pages (the already popped up screens), I add the onUnload event to the body-tag, and I open a new, tiny popup window containing the following script:

if (this.opener.closed)
// the questionnaire popup was closed
// refresh the status page of the main site
var popup = this.opener;
// window wasn't closed
// user refreshed the page, clicked a link,
// or some other postback occured
// nothing needs to be done in my case, but it is possible

Each test (consisting of a questionnaire, summary and HTML report) contains this kind of body tag:'XListener.html', 'XListener', 'menubar=no,location=no,status=yes,copyhistory=no;').blur();

Of course you can add any window attributes you like, I had to shorten the list for layout reasons 🙂

Because nothing is contained in the page I call, you don’t want it to be very big (I set mine at 1×1, and open @ left=0, top=0). The blur() command forces the focus off of the window. Optionally, you could do self.focus() on the caller window, but because I immediately close the listener window, this is not necessary.

The only main drawback of this solution is the popup window, as the user will notice it flashing by… I haven’t yet tried if it can be done without loading an actual web page (XListener.html), but I’m afraid it’s the only way of seeing if another window has been closed or not…


Author: pleinolijf

father | volleyballer | software engineer

One thought on “Capturing the Closing of a Window (‘X’) in JavaScript

  1. Hi,

    I need to how to close popup only with ‘X” button in



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s