Get HTML inside iframe using jQuery

2019-01-05 01:50发布

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.

标签: jquery iframe
10条回答
你好瞎i
2楼-- · 2019-01-05 02:28

this works for me because it works fine in ie8.

$('#iframe').contents().find("html").html();

but if you like to use javascript aside for jquery you may use like this

var iframe = document.getElementById('iframecontent');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var val_1 = innerDoc.getElementById('value_1').value;
查看更多
再贱就再见
3楼-- · 2019-01-05 02:28

Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id):

$('#iframe').get(0).contentWindow.document.body.innerHTML
查看更多
你好瞎i
4楼-- · 2019-01-05 02:28

This can be another solution if jquery is loaded in iframe.html.

$('#iframe')[0].contentWindow.$("html").html()
查看更多
5楼-- · 2019-01-05 02:29
$('#iframe').load(function() {
    var src = $('#iframe').contents().find("html").html();
    alert(src);
});
查看更多
登录 后发表回答