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
-
2Is the irfame src on the same domain? What you posted should work, what happens? (also you should accept some answers!)Alex K.– Alex K.2011年04月29日 18:06:44 +00:00Commented Apr 29, 2011 at 18:06
-
Undeleted it, the original question I read as asking how to get an iframe referenceAlex K.– Alex K.2011年04月29日 18:11:36 +00:00Commented Apr 29, 2011 at 18:11
3 Answers 3
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.
2 Comments
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.
Comments
document.getElementById('iframeResult').contentWindow.document.getElementById('buttonId')
where iframeResult is Id of iframe and buttonId is Id of element