【问题标题】:how to access the window of the html page in the iframe of another html page如何在另一个html页面的iframe中访问html页面的窗口
【发布时间】:2015-12-19 15:50:58
【问题描述】:

我的问题很简单,假设我有一个名为goal.html的html文件:

<html>
.
.
.
<body>
...
<iframe id="main_display" src="../pages/main.html" width=300 height=300><iframe> 
.
.
.

现在我在main.html 中写了一行javascript,比如window.a ="a"

现在我的问题是当我在goal.html 时如何获得window.a 的值

在搜索了一些东西并在谷歌开发工具上花了一些时间之后,我发现了一些相关的东西,它是 iframe.contentWindow 它返回一个对象但是当我尝试打开(我的意思是展开)它时,它显示了一个错误:

Uncaught [object DOMException]

那么我该怎么做呢?

【问题讨论】:

  • 试过 contentWindow.document 还是 contentDocument?见stackoverflow.com/a/1452885/1998238
  • 它给了我一个错误:Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
  • 如果contentWindow 不适合你,试试这个:var myFrame = document.getElementById("main_display").contentDocument;
  • 好吧,我明白了,所有这些东西都不能在 chrome 上运行,但在 Firefox 上运行良好,但为什么呢?

标签: javascript html iframe


【解决方案1】:

这应该适用于 goat.html

var childValue = document.getElementById("main_display").contentWindow.a;

【讨论】:

  • 给我一个错误:Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
  • 您尝试访问的 iframe url 位于不同的域中?由于Same Origin Security Policy,任何浏览器都会阻止任何试图访问具有其他来源的框架的脚本。
【解决方案2】:

奇怪的是它不能在 Chrome 上运行。我建议你尝试把它放在.ready.load 函数中。

$(function () {  
    $("#myiframe").load(function () {                        
        frames["myframe"].document.body.innerHTML = htmlValue;
    });
});

更多详情,请查看answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多