跨域获取iframe javascript内部的iframe属性

Get iframe attributes inside iframe javascript with cross domain

本文关键字:iframe 属性 内部 javascript 获取      更新时间:2023-09-26

如何在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')) 

若iframeurl和浏览器用户相同,我就可以得到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属性。

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

例如:

在父html:<iframe src="/x?a=1"></iframe>

在iframe JavaScript:window.location.search

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

在您的情况下,您可以将iframe属性src设置为localhost:8092,这样您就有了一个具有相同位置(和相同域名)的iframe,并且您可以访问它的数据。