简体   繁体   中英

Get contents from second iframe

At the moment I can retrieve the contents of the first iframe on a web page that is not mine with $('iframe').contents()

From this I can get the body tag by doing $('iframe').contents().find('body') . The results are what is expected

However, I an trying to get the body tag of the second iframe. By doing `$('iframe').eq(1) I can get the second iframe, but $('iframe').eq(1).contents() gets nothing.

How can I get the contents of the second iframe?

A lot of the Fiddles and such may not be a good test place. There are complications with CORS. Here is an example that works:

https://jsfiddle.net/Twisty/037yueqj/9/

HTML

<iframe id="frame-1"></iframe>
<iframe id="frame-2"></iframe>

JavaScript

$(function() {
  var f1 = $("#frame-1"),
    f2 = $("#frame-2"),
    frames = $("iframe");
  f1.contents().find("body").html("<strong>Frame 1</strong>");
  f2.contents().find("body").html("<strong>Frame 2</strong>");
  console.log(frames.eq(0).contents().find("body").text());
  console.log(frames.eq(1).contents().find("body").text());
});

If you give them unique IDs or classes, you can just call on the proper selector. You can call on a wider selector and use .eq() or iterate with .each() .

Had to use --disable-web-security in chromium to access contents in an iframe from another url

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