【问题标题】:how to make html <a target='_parent'> point to the same as javascript window.opener?如何使 html <a target='_parent'> 指向与 javascript window.opener 相同?
【发布时间】:2015-11-13 00:55:49
【问题描述】:

在我的项目中,我有一个主页,用户登录并查看主表,以及许多在不同窗口中打开的附加页面。

当登录超时时,用户应该不能访问任何内容。在主页中,我再次给出了登录页面的链接。在子窗口中,我不能这样做,因为我不希望在子窗口中完成登录。

在javascript中,我可以使用window.opener来访问主窗口(因为每个子窗口都是用window.open打开的)。如何在 html a 标记中做到这一点?

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>");
}

问题是:这段代码在子窗口中打开了登录页面,所以target='_parent' 不像我想象的那样行事。如果有的话,实现这一目标的正确方法是什么?

【问题讨论】:

    标签: javascript html href window.opener


    【解决方案1】:

    如果您为原始窗口的window.name 属性分配一些值(例如"master"),那么您可以简单地通过&lt;a target="master"&gt; 定位该窗口。

    这里是 dataURI 格式的简单概念验证:复制并粘贴到您的地址栏,仅限 Chrome/Firefox;在这里很难模拟任何其他方式:

    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>
    

    甚至有相当有趣的可能性从奴隶中设置主人(开启者)name,但前提是两者共享相同的来源:

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

    MDN: window.name

    【讨论】:

    • 奇怪,我只按照你的第一段,它工作。但在此之前,我只能为每个 php 文件打开一个窗口,现在我打开了许多相同的 php 文件。知道为什么吗?
    【解决方案2】:

    你不能。

    target 只允许您在当前窗口/选项卡中的框架之间导航。

    只有 JavaScript 可以访问开启程序。我还没有测试以下内容,但它应该会为您指明正确的方向。

    document.querySelector('.login-expired a').addEventListener('click', open_in_opener);
    
    function open_in_opener(event) {
      window.opener.location = this.href;
      event.preventDefault();
    }
    &lt;p class="login-expired"&gt;You don't have authorization to access this page. Please, &lt;a href='index.php'&gt;go back to main screen and login&lt;/a&gt;.&lt;/p&gt;

    【讨论】:

      【解决方案3】:

      目标适用于框架和 iframe。你需要像这样处理javascript

       <a href="#" onclick="window.opener.location.href = 'index.php'; return false;">
      

      祝你好运

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-05
        • 2015-02-16
        • 2019-07-23
        • 2017-02-19
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多