【问题标题】:Allow iframe links to target parent frames cross domain允许跨域目标父框架的 iframe 链接
【发布时间】:2023-03-25 13:54:01
【问题描述】:

我有 2 个域。 domain1 上的一个页面使用 iframe 从 domain2 加载内容。如何允许来自 domain2 的链接(在 iframe 内)在 domain1 的完整父框架中打开?

我一直在查看 IE application attribute 和 w3c 的新 sandbox attribute,但我不确定如何实现这些以及它们是否兼容跨浏览器。有没有其他技巧可以解决这个问题?

我可以用 javascript 像素做些什么吗?

【问题讨论】:

  • 你试过target="_parent" iframe中的链接吗?
  • 是的,页面在新窗口中加载,chrome抛出错误:Unsafe JavaScript attempt to initiate a navigation change

标签: javascript html security


【解决方案1】:

您需要使用postMessage() 跨域发送数据。

1.编码 domain2.com 上的链接(iframe 内的链接):

<a href="javascript:;" onclick="top.postMessage('newpage.html','http://domain2.com')"></a>

2。在 domain1.com(父页面)的页面头部捕捉消息并导航:

window.addEventListener( "message", function(e){
    window.location.href = e.data  //navigates to newpage.html
}, false)

如果您需要更多详细信息,请参阅类似问题 here。对于on this page 看起来相当全面。

【讨论】:

    【解决方案2】:

    您可以使用 Javascript 覆盖 A 标记并将它们指向 window.parent。

    http://jfcoder.com/test/iframe_open.html

    window.onload = function(){
        var a = document.getElementsByTagName('a');
        for (var i = 0; i < a.length; i++) {
            a[i]['_href'] = a[i].href;
            a[i].href = '#';
            a[i].onclick = function(){
                window.parent.location = this._href;
                return false;
            }
        }
    }
    

    显然,这不是您一定要在最终代码中使用的代码,只是一个概念证明。但这适用于 IE9、FF4 和 Chrome(当前)没有任何问题。

    【讨论】:

    • 这和&lt;a href='#' onclick='window.parent.location="http://www.google.com/";return(false);'&gt;click&lt;/a&gt;一样吗?因为这也会引发安全错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2011-02-22
    • 2014-11-14
    • 1970-01-01
    • 2015-12-19
    • 2019-02-17
    相关资源
    最近更新 更多