Brian McGinity
Brian McGinity

Reputation: 5935

Javascript: How to get a list of all open windows

Suppose you open a handful of windows with:

  window.open(url1,'win1');
  window.open(url2,'win2');
  window.open(url3,'win3');

(each window has a unique name)

And then you refresh the page.

The 3 popup windows are still open. Is there a way to list the names of all of the open windows and close them?

This is not a duplicate question.

In this question the browser is being refreshed, so you cannot simply use a global array to keep track of child windows.

This is not a duplicate question.

Upvotes: 8

Views: 27354

Answers (2)

Vozzie
Vozzie

Reputation: 455

Try postMessage to communicate between existing windows within the same domain. That's how i'm going to try and solve the same problem. See: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

index.htm

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>pop</title>
  </head>
  <body>

    <script>

var pops = [];

window.onmessage = function(e)
{

    // todo: check domain 
    // if( e.origin )
    var data;
    try
    {
        data = JSON.parse(e.data);
    }
    catch(e)
    {
        // fail silent...?
        return;
    }
    switch(data.event)
    {
    case "RestoreOpenWindow":
        onClosePopup(e.source.name);
    case "QueryOpenWindows":
        pops.push(e.source);
        updateLabel();
        break;
    }
};

window.onload = function()
{
    window.onClosePopup = onClosePopup;
    updateLabel();
};

window.onbeforeunload = function()
{
    for(var i = 0; i < pops.length; i++) pops[i].queryOpenPopups();
};

function onClosePopup(name)
{
    for(var i = pops.length - 1; i >= 0; i--)
        if(pops[i].name === name)
            { pops.splice(i, 1); break; }
    updateLabel();
};

function openPopup()
{
    pops.push(window.open("pop/popup.htm", "pop" + pops.length, ' '));
    updateLabel();
    setTimeout(function(){
        alert('Click ok to refresh...');
        location.href = location.href;
    }, 5000);
}

function updateLabel()
{
    document.getElementById("total").innerHTML = pops.length;
    var html = [];
    for(var i = 0; i < pops.length; i++)
        html.push(pops[i].name);
    document.getElementById("names").innerHTML = html.join("<br"+"/"+">");
}


    </script>
    <button onclick="openPopup()">open popup and refresh after 5 seconds (...allow em popups...)</button></br>
    <span>total: </span><span id="total"></span></br>
    <span id="names"></span></br>
  </body>
</html>

popup.htm

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>pop</title>
  </head>
  <body>

    <script>

window.queryOpenPopups = function()
{
    var count = 0;
    var hInterval = setInterval(function () {
        try
        {
            if(window.opener)
            {
                window.opener.postMessage(JSON.stringify({"event": "QueryOpenWindows", "name": window.name}), "*");
                clearInterval(hInterval);
            } else count++;
        }
        catch(e)
        {
            count++;
        }       
        if(count > 50)window.close();
    }, 100);
};

window.onbeforeunload = function(){
    window.opener.onClosePopup(window.name);
};

// restore link with opener on refresh
window.opener.postMessage(JSON.stringify({"event": "RestoreOpenWindow", "name": window.name}), "*");

window.onload=function(){ document.getElementById("name").innerHTML = window.name; };
    </script>       
    <span id="name"></span>
  </body>
</html>

Upvotes: 3

Brian McGinity
Brian McGinity

Reputation: 5935

So the questions is closed, I'll post an answer based on the comments and research.

Firstly, to all who commented, thank you for helping.

Answer: There is not a built-in object which tracks opened windows and persists from page load to page load.

As Felix Kling pointed out, using localStorage is a possible work-around.

Upvotes: 6

Related Questions