【问题标题】:Access parent from iframe even though domains don't match?即使域不匹配,也可以从 iframe 访问父级?
【发布时间】:2012-08-20 20:38:36
【问题描述】:

我有一个 javascript 脚本正在尝试访问父级的 iframe 中运行,但出现以下错误:

Unsafe JavaScript attempt to access frame with URL mysite.com from frame with URL myothersite.com?. Domains, protocols and ports must match.

iframe html 位于不同的域中,但我认为这无关紧要。这是产生 JS 错误的代码:

var parent_site = parent.document;

有没有办法解决这个问题?

【问题讨论】:

  • 出于安全原因,您不能这样做。谷歌“XSS 漏洞”
  • 不,如果父窗口来自另一个域,则无法访问父窗口,除非您可以控制它。

标签: javascript dns


【解决方案1】:

如果父域是 iframe 域的尾随部分(即 iframe 是 child.parent.com,父域是 parent.com),您可以使用 document.domain = "parent.com" 设置 iframe 文档的域并避免此问题。

如果父域和 iframe 的域不相关,则无法解决。

【讨论】:

    【解决方案2】:

    对CORS(跨域资源共享)做一些研究:http://www.w3.org/TR/cors/

    您基本上需要将其添加到父域的 .htaccess 中:

    Header set Access-Control-Allow-Origin *
    Header set Access-Control-Allow-Headers x-requested-with
    

    理想情况下,您应该将* 替换为您希望允许访问的域。

    【讨论】:

      猜你喜欢
      • 2017-11-06
      • 1970-01-01
      • 2014-01-17
      • 2012-04-05
      • 2012-11-25
      • 2012-09-04
      • 2011-10-03
      • 1970-01-01
      相关资源
      最近更新 更多