【问题标题】:Get iframe attributes inside iframe javascript with cross domain使用跨域获取 iframe javascript 中的 iframe 属性
【发布时间】:2020-12-16 04:56:23
【问题描述】:

如何在 iframe javascript 代码中获取 iframe 属性

<div>
<iframe src="http://192.168.0.108:8092/"
            name="otherDomain"
            width="100%"
            height="600px"
            style="border: 0;"
            data-auth-token="xyz"
            data-auth-key="abc"
      >
</div>

我正在尝试

console.log(window.frameElement.getAttribute('data-auth-token')) 

如果 iframe url 和浏览器用户相同,我可以获取 iframe 属性。如果网址不同,我会收到以下错误。

Uncaught SecurityError: Failed to read the 'frame' property from 'Window': Blocked a frame with origin "http://192.168.0.108:8092" from accessing a frame with origin "http://localhost:8092". Protocols, domains, and ports must match. 

是否可以在 JavaScript 中获取跨域 iframe 属性。

【问题讨论】:

    标签: javascript jquery html angularjs


    【解决方案1】:

    很遗憾,您无法使用引用另一个域的 iframe。浏览器会自动阻止所有试图从另一个域访问框架的脚本。如果这样的事情是可能的,那将是一个巨大的安全漏洞。

    在您的情况下,您可以将iframe 属性src 设置为localhost:8092,因此您将拥有一个具有相同位置(和相同域名)的iframe,并且您将能够访问其数据。

    【讨论】:

    • 感谢您的解释@Marco Bonelli。我想错了。
    【解决方案2】:

    您无法从 iframe 内部访问属性,但可以访问查询字符串。

    例如:

    在父 html 中:&lt;iframe src="/x?a=1"&gt;&lt;/iframe&gt;

    在 iframe JavaScript 中:window.location.search

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多