简体   繁体   中英

Access cross-domain iframe elements using JavaScript

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>

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM