Search code examples
javascripthtmlhrefwindow.opener

how to make html <a target='_parent'> point to the same as javascript window.opener?


In my project, I have a main page, where the user logs in and sees the main tables, as well as many additional pages, which open in different windows.

When the login timeout, the user should not be able to access any content. In the main page, I give a link to the login page again. In the sub-windows, I can't do that, because I don't want the login to be done in a sub-window.

In javascript, I can use window.opener to have access to the main window (since each sub-window is opened with window.open). How can I do that inside an html a tag?

if (!login_check($conn)) { // tests if the user is connected
    // exits with a message, if not connected anymore
    exit("<p>You don't have authorization to access this page. Please, <a href='index.php' target='_parent'>go back to main screen and login</a>.</p>");
}

The problem is: this code opens the login page on the sub-window, so target='_parent' does not act like I have thought. What is the proper way to achieve this, if any?


Solution

  • If you assign window.name property of the original window some value (e.g. "master") then you can target that window simply by <a target="master">.

    Here is simple proof-of-concept in dataURI format: copy & paste to your location bar, Chrome/Firefox only; hard to simulate any other way here:

    data:text/html,<script>window.name="master";</script>I am master. <button onclick="window.open('data:text/html,<a target=\'master\' href=\'data:text/plain,content for master from slave\'>Replace content of master</a>')">Open slave</button>
    

    There is even quite amusing possibility to set masterʼs (openerʼs) name from within slave, but only if both share same origin:

    <a onclick='if(window.opener)window.opener.name=this.target=Math.random()' href='whatever'>Open whatever in opener, if any</a>
    

    MDN: window.name