Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

Get HTML inside iframe using jQuery

Here is my situation.

I have a file called iframe.html, which contains the code to for a image slideshow. The code is somewhat like

<html>
  <head>
    <!-- Have added title and js files (jquery, slideshow.js) etc. -->
  </head>

  <body>
    <!-- Contains the images which are rendered as slidehow. -->
    <!-- have hierarchy like 'div' inside 'div' etc. -->
  </body>
</html>

Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in index.html, they can add by adding following lines:

<iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe>

This will bring the complete HTML code from iframe.html to index.html, now I need a way to access the elements in the iframe to adjust some of their properties.

Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this?

I tried with no success to access the iframe components from index.html by something like

$('#iframe').contents();

but get the error:

TypeError: Cannot call method 'contents' of null

So, I think to implement the logic in iframe.html where the slideshow should check the width and height of parent and set its height accordingly.

I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This line will retrieve the whole HTML code of the frame. By using other methods instead of innerHTML you can traverse DOM of the inner document.

document.getElementById('iframe').contentWindow.document.body.innerHTML

Thing to remember is that this will work only if the frame source is on the same domain. If it is from a different domain, cross-site-scripting (XSS) protection will kick in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...