Javascript: 访问 iframe 的内容

I would like to manipulate the HTML inside an iframe using jQuery.

I thought I'd be able to do this by setting the context of the jQuery function to be the document of the iframe, something like:

$(function(){ //document ready
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
});

However this doesn't seem to work. A bit of inspection shows me that the variables in frames['nameOfMyIframe'] are undefined unless I wait a while for the iframe to load. However, when the iframe loads the variables are not accessible (I get permission denied-type errors).

Does anyone know of a work-around to this?

转载于:https://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe

csdnceshi51
旧行李 one way is chrome extensions
7 年多之前 回复
csdnceshi73
喵-见缝插针 It’s more cross-browser to use .contentWindow.document than .document on the iframe element. I’ll suggest the change above.
9 年多之前 回复
csdnceshi67
bug^君 No, because that would be cross-site scripting, which is prohibited for security reasons. My solution was to use a proxy: feed the HTML in the IFRAME verbatim through my own site so it's no longer cross-site fro mthe browser's perspective.
10 年多之前 回复
csdnceshi60
℡Wang Yan if it is a other domain,is there still a way to access its content or register an event
大约 11 年之前 回复
csdnceshi57
perhaps? What does the iFrame contain - is its src set to another domain?
接近 12 年之前 回复

12个回答

I think what you are doing is subject to the same origin policy. This should be the reason why you are getting permission denied type errors.

csdnceshi71
Memor.の For the record, I just set up something similar : if you don't want the result to be incredibly slow, just set up your web server to directly reroute asset requests (CSS/JS/images) to the original website, so your proxy only manages HTML requests. I'm browsing a distant site under localhost right now and it's absolutely transparent :)
大约 7 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Potentially any of the methods in the accepted answer here: stackoverflow.com/questions/3076414/… or others (like using your own domain as a proxy), depending upon what you want to achieve.
大约 7 年之前 回复
csdnceshi64
游.程 In this case, he means use the http server that is serving your domain's page as the proxy - request the content from the 3rd party site and forward it on in the http response to the client. As you can probably guess, it quickly impacts the responsiveness of your site as previously parallel requests are instead executed in series with your server as a potential bottleneck.
7 年多之前 回复
csdnceshi67
bug^君 Can you suggest any framework/api/design pattern for implementing this proxy solution. Any links to example or tutorial etc? I have tried to search but couldn't find any.
8 年多之前 回复
csdnceshi61
derek5. Best bet is to proxy the content of the iframe on your site, if you can...
8 年多之前 回复
csdnceshi54
hurriedly% so what's the workaround solution ?
大约 9 年之前 回复

If the <iframe> is from the same domain, the elements are easily accessible as

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

Reference

weixin_41568126
乱世@小熊 For anyone wondering about why this isn't the accepted answer - note the dates. This came a year after the question was asked; would be nice if OP would change the accepted answer, but 5+ years on it's not likely. May be a question for Meta if it bothers anyone; I found what I needed and upvoted.
大约 5 年之前 回复
csdnceshi71
Memor.の Security error: See other answer about same origin policy. No method contents on iframe: It's a jQuery method... Notice the $(...)
大约 6 年之前 回复
csdnceshi60
℡Wang Yan I am getting a security error... Failed to read the 'contentDocument' property from 'HTMLIFrameElement' Is there a way to pass it?
6 年多之前 回复
weixin_41568208
北城已荒凉 I noticed $("#iframe")[0].contentWindow.document which was always returning an empty document object in our code, changing it to $("#iframe").contents()[0] returns the correct document object! In my case, both the iframe and parent page were from the same domain.
接近 7 年之前 回复
weixin_41568174
from.. Laghari the reference link above gives a malicious website warning when you click on it! :(
接近 7 年之前 回复
csdnceshi64
游.程 There is no method called contents for the iframe.
大约 7 年之前 回复
csdnceshi50
三生石@ Then you get the IFrame the same way you'd get any other id-less content with jQuery: you select the appropriate <IFrame> tag with CSS, using class names and attribute values to narrow it down if necessary.
8 年多之前 回复
csdnceshi78
程序go What if the iframe has no "id" ?
8 年多之前 回复
csdnceshi75
衫裤跑路 my guess is that OP's problem is indeed the same origin policy, in which case this answer is not a solution for him.
接近 9 年之前 回复
csdnceshi72
谁还没个明天 You have to use a proxy to get the HTML in your origin. For example, johnchapman.name/…
9 年多之前 回复
weixin_41568127
?yb? Knowing about the same origin policy is great but this is the answer that does what the OP wanted. Why did the other answer get picked as the right one?
接近 10 年之前 回复

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

csdnceshi77
狐狸.fox Which usage of ready should be load? Both?
7 年多之前 回复
csdnceshi67
bug^君 A couple of notes on this code: you should use iframe.contentDocument instead of .document, and you should use .load() instead of .ready() to avoid the wait. (Not perfect, but better)
大约 11 年之前 回复
weixin_41568196
撒拉嘿哟木头 The ready function works. However, it seems that it doesn't wait for the contents of the iframe to finish loading -- only for the parent document even when invoked on the contents of the iframe itself. I imagine it is also because of the same origin policy.
接近 12 年之前 回复
csdnceshi55
~Onlooker Sooo... the ready function doesn't work?
接近 12 年之前 回复
weixin_41568196
撒拉嘿哟木头 actually... nevermind, it seems that the wait is still required even when doing this.
接近 12 年之前 回复
weixin_41568196
撒拉嘿哟木头 this is a good idea, in fact I was trying it just as you answered. However, it doesn't work around the permission denied (it does address my having to wait before starting to access the iframe stuff)
接近 12 年之前 回复

I prefer to use other variant for accessing. From parent you can have a access to variable in child iframe. $ is a variable too and you can receive access to its just call window.iframe_id.$

For example, window.view.$('div').hide() - hide all divs in iframe with id 'view'

But, it doesn't work in FF. For better compatibility you should use

$('#iframe_id')[0].contentWindow.$

$(document).ready(function(){
    $('#frameID').load(function(){
        $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
    });
});
weixin_41568126
乱世@小熊 comments removed to prevent confusion. apologies.
5 年多之前 回复
csdnceshi78
程序go leaving the original comment didn't make me shame you, but I did waste like 30 seconds trying to understand a non-issue :) So removing this whole discussion about a plagiarizing answer might be best.
5 年多之前 回复
csdnceshi57
perhaps? Um, actually this answer came first, so if anything, the other answer was the copy
5 年多之前 回复
weixin_41568208
北城已荒凉 i need to get the i frame content not to set the body ..... When i do the above it doesn't works always return empty Body
8 年多之前 回复

Use

iframe.contentWindow.document

instead of

iframe.contentDocument
weixin_41568184
叼花硬汉 Nowadays, it doesn't work even from console
5 年多之前 回复
csdnceshi77
狐狸.fox Or a 'bookmarklet' - en.wikipedia.org/wiki/Bookmarklet
5 年多之前 回复
weixin_41568134
MAO-EYE This should be the accepted answer. Saved my life and works when the iframe is from a different domain; although as mentioned, only in the console.
6 年多之前 回复
csdnceshi67
bug^君 I believe it will only work for other domains if you're doing it from the console. From a script, access will not be allowed.
9 年多之前 回复
weixin_41568183
零零乙 Great answer. This works for iFrames in other domains. I tried this in the console on Safari and Firefox.
接近 10 年之前 回复

I find this way cleaner:

var $iframe = $("#iframeID").contents();
$iframe.find('selector');

You can use window.postMessage to call a function between page and his iframe (cross domain or not).

Documentation

page.html

<!DOCTYPE html>
<html>
<head>
    <title>Page with an iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'page',
        variable:'This is the page.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    function iframeReady(iframe) {
        if(iframe.contentWindow.postMessage) {
            iframe.contentWindow.postMessage('Hello ' + Page.id, '*');
        }
    }
    </script>
</head>
<body>
    <h1>Page with an iframe</h1>
    <iframe src="iframe.html" onload="iframeReady(this);"></iframe>
</body>
</html>

iframe.html

<!DOCTYPE html>
<html>
<head>
    <title>iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'iframe',
        variable:'The iframe.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    $(window).on('load', function() {
        if(window.parent.postMessage) {
            window.parent.postMessage('Hello ' + Page.id, '*');
        }
    });
    </script>
</head>
<body>
    <h1>iframe</h1>
    <p>It's the iframe.</p>
</body>
</html>

I create a sample code . Now you can easily understand from different domain you can't access content of iframe .. Same domain we can access iframe content

I share you my code , Please run this code check the console . I print image src at console. There are four iframe , two iframe coming from same domain & other two from other domain(third party) .You can see two image src( https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif

and

https://www.google.com/logos/doodles/2015/arbor-day-2015-brazil-5154560611975168-hp2x.gif ) at console and also can see two permission error( 2 Error: Permission denied to access property 'document'

...irstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument...

) which is coming from third party iframe.

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<p>iframe from same domain</p>
  <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="iframe.html" name="imgbox" class="iView">

</iframe>
<p>iframe from same domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
   src="iframe2.html" name="imgbox" class="iView1">

</iframe>
<p>iframe from different  domain</p>
 <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif" name="imgbox" class="iView2">

</iframe>

<p>iframe from different  domain</p>
 <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="http://d1rmo5dfr7fx8e.cloudfront.net/" name="imgbox" class="iView3">

</iframe>

<script type='text/javascript'>


$(document).ready(function(){
    setTimeout(function(){


        var src = $('.iView').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 2000);


    setTimeout(function(){


        var src = $('.iView1').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 3000);


    setTimeout(function(){


        var src = $('.iView2').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 3000);

         setTimeout(function(){


        var src = $('.iView3').contents().find("img").attr('src');
    console.log(src);
         }, 3000);


    })


</script>
</body>

If the iframe src is from another domain you can still do it. You need to read the external page into PHP and echo it from your domain. Like this:

iframe_page.php

<?php
    $URL = "http://external.com"

    $domain = file_get_contents($URL)

    echo $domain
?>

Then something like this:

display_page.html

<html>
<head>
  <title>Test</title>
 </head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script>

$(document).ready(function(){   
    cleanit = setInterval ( "cleaning()", 500 );
});

function cleaning(){
    if($('#frametest').contents().find('.selector').html() == "somthing"){
        clearInterval(cleanit);
        $('#selector').contents().find('.Link').html('ideate tech');
    }
}

</script>

<body>
<iframe name="frametest" id="frametest" src="http://yourdomain.com/iframe_page.php" ></iframe>
</body>
</html>

The above is an example of how to edit an external page through an iframe without the access denied etc...

csdnceshi75
衫裤跑路 to php newbies: ; is needed in statements in iframe_page.php, e.g. $URL = "http://external.com";
大约 3 年之前 回复
csdnceshi61
derek5. Would this work when the content of iframe is supposed to be JS?
3 年多之前 回复
csdnceshi58
Didn"t forge Yes and yes. But sometimes it's the only way... Some sites however offer JS API's to get data in a structured way, cross-domain. In such cases you should use that instead of proxying to prevent the issues you mentioned
大约 6 年之前 回复
csdnceshi62
csdnceshi62 But doesn't it break the layout when the target page has non-absolute URLs and relative links?
接近 7 年之前 回复
csdnceshi68
local-host If you on Ruby on Rails it set header X-Frame-Options=DENY. So to make iFrame proxy add response.headers["X-Frame-Options"] = nil to proxy action
7 年多之前 回复
csdnceshi78
程序go I know it's an old thread, but won't this method have consequenses for the 1: the loading time, as the server first loads an external url and then sends it to the client, and 2: for the data usage of your own hosting package?
大约 8 年之前 回复
csdnceshi63
elliott.david is it illegal in any way to do this?
8 年多之前 回复
weixin_41568134
MAO-EYE Be mindful: there is a reason why the same origin policy exists, and this answer's proposal is not immune to it.
接近 9 年之前 回复
weixin_41568126
乱世@小熊 What Mark means is that the browser won't send any cookies intended for the foreign domain to your domain, (for example it wouldn't send cookies from bank.com to mydomain.com), and so the user will see the page as it would be without cookies (ie. logged out)
9 年多之前 回复
csdnceshi53
Lotus@ As far as the browser knows, no foreign domain is involved. The browser will talk to your server (including cookies, posted data and headers), which will in turn talk to the foreign domain. (Unless it uses tricks like cookies set/read by images, etc, which could be fixed by parsing the HTML and routing them through PHP as well.)
9 年多之前 回复
csdnceshi56
lrony* but the browser won't send cookies for the foreign domain to your PHP script
9 年多之前 回复
csdnceshi53
Lotus@ You can easily send cookies, posted data, HTTP headers and whatnot if you implement it with the curl extension. php.net/manual/en/book.curl.php
9 年多之前 回复
csdnceshi69
YaoRaoLov Of course, because your server is getting the remote page not the user's browser, no cookies will be sent to the remote page. YMMV.
接近 10 年之前 回复
共12条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐