Check if Popup Window Closed

Sometimes you will want to use a popup window for an antiquated system and need to maintain a reference to the popup window so that when the popup loses focus you can bring it back in focus with a click of a button. The following script will allow you to do that.

In brief, the script opens a window when a button is clicked, if it loses focus you just need to click the button again to get it back. The script also deals with the fact that the user may close their browser window, navigate away from the main page or refresh the current browser window.


<script type="text/javascript" src="">

<button id="button">Click Me!</button>
<script type="text/javascript">
var win;
$(window).load(function() {

function openPopup() {
var left = (screen.width/2);
var top = (screen.height/2);
var popWidth = 800;
var popHeight = 600;
var popTop = top - popHeight/2;
var popLeft = left - popWidth/2;
if(win && !win.closed){ //checks to see if window is open
} else {
win ='', 'Example_window', 'height=' + popHeight + ',width=' + popWidth + ',resizeable=0, top=' + popTop + ', left=' + popLeft);

function polling(){
if (win && win.closed) {
alert('popup window is closed.');
timer = setInterval('polling()',1000);

* This javascript file checks for the brower/browser tab action.
* It is based on the file menstioned by Daniel Melo.
* Reference:
var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("Browser window closed");

function wireUpEvents() {
* For a list of events that triggers onbeforeunload on IE
* check
window.onbeforeunload = function() {
if (!validNavigation) {

// Attach the event keypress to exclude the F5 refresh
$('html').bind('keypress', function(e) {
if (e.keyCode == 116){
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;


// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {