Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Find browser windows open with the same domain

Is there a way to get a list of all the open browser windows if they are from the same domain as the window that is trying to get the list?

like image 829
Johann Avatar asked Oct 26 '11 16:10

Johann


1 Answers

In general, no.

Unless there is a "connection" between the windows (e.g., one window opened all the other using window.open), browser windows can't interact because of security reasons.

Edit:

If you assign a name to your window, you can regain control over it after refreshing the parent page.

  1. windowVar = window.open('somePage.html', 'windowName'); opens a child window with name windowName.

  2. After refreshing the parent page, windowVar = window.open('', 'windowName'); re-associates the variable windowVar with the window of name windowName.

  3. Now, windowVar.location.href= 'logout.html'; lets you log out your user.

Edit:

Assuming you use PHP, you could do something like this:

Create logged.php with a function logged_in that verifies if the session ID is still valid.

<?php
    if (isset($_GET['sid']))
            if (logged_in($_GET['sid']))
            echo "in";
    else
            echo "out";
?>

Include check() function in your pages.

function check()
{
    var url = "http://redtwitz.com/test/logged.php?sid=" + sessionId;
    var request;
    try
    {
        request = new XMLHttpRequest();
    }
    catch(error1)
    {
        try
        {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(error2)
        {
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    request.open("GET", url, false);
    request.setRequestHeader("User-Agent",navigator.userAgent);
    request.send(null);
    if(request.status==200)
        if(request.responseText == "out")
            window.location.href = "logout.html";
}

Call check function every 5 seconds.

<body onload="setInterval(check, 5000);">
like image 131
Dennis Avatar answered Sep 27 '22 19:09

Dennis