开发者

How can I access the contents of a frame or iframe with JavaScript or JQuery?

开发者 https://www.devze.com 2023-01-14 23:39 出处:网络
I\'m trying开发者_如何学编程 $(document).ready(function(){ var myIFrame = document.getElementById(\"myIframe\");

I'm trying

开发者_如何学编程
$(document).ready(function(){   
    var myIFrame = document.getElementById("myIframe");
        var content = myIFrame.contentWindow.document.body.innerHTML;
    alert(
        content
    );
})

but I get an access denied error I guess because what I have loaded in the frame is Google. Is what I want to do even possible? The document must be an external one (like Google). And I would like to loop through all elements in the document. I'm a newbie on JS and JQuery so I might be missing a very basic thing.


You can't because of the Same Origin Policy, implemented in all common browsers.
The protocol, host, domain and port of two IFRAME pages must match(having the same origin) to allow javascript to communicate between them.

If you want to enable cross domain communication in javascript you need some cooperation from the other domain.

Now if you plan to read something less ambitious than google.com, and the other domain is ready to communicate with you, here are two techniques:

  1. For modern browsers you can use parent.postMessage from the IFRAME and have a listener in the main page to receive a string message.
     
  2. For older browsers you can use tricks like passing string data i.e. through windows.name or the window.location.hash
    But with those tricks you will have to poll with a setInterval to check for changes.


No, this is called cross site scripting (XSS), and is disabled for security.


Try doing this:

$(document).ready(function(){
    iframe = $('#myIframe');
    alert($(iframe).contents());
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号