javascript - 错误 : Permission denied to access property "document"

标签 javascript html iframe xss access-control

我有一个包含 iframe 的 HTML 文档。每当我尝试使用 JS 访问或修改此 iframe 时,我都会收到 Error: Permission denied to access property "document"

我正在使用 frame.contentWindow.document.body.innerHTMLframe.contentWindow.document.body.onload 或类似的属性来访问或修改 iframe。 (在给定的代码中,iframe 被称为 frame。)

对于我正在开发的网络应用程序,访问这些属性是必要的,没有这些(或类似的替代方案)我就做不到。

最佳答案

访问并修改 iframe 中的网页其他网站的 s 被称为 Cross-site scriptingXSS,它是恶意黑客用来掠夺毫无戒心的受害者的一种技术。

浏览器制造商实现了名为“同源策略”的策略,以防止此类行为和任意执行 JS 代码。

可以通过在 iframe 中托管父文档和文档来防止此错误在相同的域和子域中,并确保使用相同的协议(protocol)加载文档。

不兼容页面的示例:

  1. http://www.example.org & http://www.example2.com
  2. http://abc.example.org & http://xyz.example.com
  3. http://www.example.org & https://www.example.com

Cross-Origin Resource Sharing是这个问题的解决方案。

例如:
如果http://www.example.com想分享http://www.example.com/hellohttp://www.example.org , 标题可以与文档一起发送,如下所示:

Access-Control-Allow-Origin: http://www.example.org

要用 HTML 发送它,只需将它放在 <META HTTP-EQUIV="..."> 中标签,像这样:

<head>
    ...
    <META HTTP-EQUIV="Access-Control-Allow-Origin" CONTENT="http://www.example.org">
    ...
</head>

关于javascript - 错误 : Permission denied to access property "document",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36333978/

相关文章:

javascript - React Native Camera - 多张照片

javascript - 向每个表格单元格添加更改事件

javascript - 如何检查 iFrame 中是否有值

javascript - 如何正确记录 React/Redux 应用程序?

javascript - Cordova - iOS 嵌套元素禁用反弹但保持速度滚动

html - 使用 Sinatra 布局生成模板 : Yields stringified version of my html

jquery - 为什么我的获取 iframe 内容高度的 jQuery 方法不能在 Firefox 中运行?

iframe - 可以在 iframe 中访问 Phonegap API 吗?

javascript - onchange 事件不接受我的 javascript 代码

javascript - 如何使淡入/淡出只发生一次