使用JavaScript访问跨域iframe元素 [英] Access cross-domain iframe elements using JavaScript

查看:155
本文介绍了使用JavaScript访问跨域iframe元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an iframe in my html page and I want to access some content from the page opened in this 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>

在此网页的来源中,

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

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

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

推荐答案

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

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.

如果您有最新的浏览器和你编码两个框架来合作(这意味着你必须控制两个框架中的JavaScript代码),有一个新功能称为窗口信息,可用于在来自不同来源的帧之间传递信息。

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 messaging that can be used to pass information between frames from different origins.

这篇关于使用JavaScript访问跨域iframe元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆