使用 JavaScript 访问跨域 iframe 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7804240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:23:11  来源:igfitidea点击:

Access cross-domain iframe elements using JavaScript

javascripthtmldomiframe

提问by Saurabh Saxena

I have an iframe in my html page and I want to access some content from the page opened in this iframe.

我的 html 页面中有一个 iframe,我想从在这个 iframe 中打开的页面访问一些内容。

<table border="1" width="100%" height="100%">
    <tr>
        <td id = "freebase_td">
        <iframe id = "freebase_frame" src="http://www.freebase.com/view/en/angelina_jolie" width="100%" height="400px"></iframe>
        </td>
    </tr>
</table>

In this web page's source,

在这个网页的源代码中,

  <h1 id="page-title">
    Angelina Jolie
  </h1>

I want to access the content in the h1 tag with id "page-title" using javascript. Could it be possible?

我想使用 javascript 访问 id 为“page-title”的 h1 标签中的内容。可能吗?

采纳答案by jfriend00

You should first read about the browser's same-origin policy. This prevents javascript from a frame or window or iframe in one origin from accessing the content or scripts in another frame in a different origin. So, if your iframe is not the same origin as the page of your script, then it cannot directly access the iframe's contents.

您应该首先阅读浏览器的同源策略。这可以防止一个源中的框架或窗口或 iframe 中的 javascript 访问不同源中另一个框架中的内容或脚本。因此,如果您的 iframe 与脚本页面的来源不同,则它无法直接访问 iframe 的内容。

If you have one of the latest browsers and you code both frames to cooperate (which means you have to control the javascript code in both frames), there is a new feature called window messagingthat can be used to pass information between frames from different origins.

如果你有一个最新的浏览器并且你编写了两个框架的代码来合作(这意味着你必须控制两个框架中的 javascript 代码),有一个叫做窗口消息的新功能可以用来在来自不同来源的框架之间传递信息.