简体   繁体   中英

How to get an element from an iframe

I want to get an element from an iframe using JavaScript. I've tried the following:

var iframe = document.getElementById("iframe id");

var iframeWindow = iframe.contentWindow || iframe.contentDocument.parentWindow;

 iframe.onload = function(){


        alert(iframeWindow.getElementById('notice'));

    };

Can anyone help me get this working?

with cross domain

thanks for reply

Assuming its all on the same domain;

var ifr = document.getElementById('the_iframes_id');
//or window.frames[x].
var doc = ifr.contentDocument || ifr.contentWindow.document;
alert(doc.getElementById('notice'));

If its not on the same domain, you cannot access it for security reasons.

document.getElementById('iframeResult').contentWindow.document.getElementById('buttonId')

where iframeResult is Id of iframe and buttonId is Id of element

You are out of luck if you want to do this across domains. Javascript's security model will not allow it.

I don't know what you are trying to accomplish, but you might be able to get what you need with server-side scripting. A Perl/PHP/Python/Ruby/whatever script generally has the possibility of retrieving any web page you'd need. It could then parse out the bit you need and return this to your Javascript via AJAX calls.

Of course this is more complicated than just using JS, and assumes that the iframe's content is not dynamic, based on cookies or other session things at this moment.

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