1

Is there any way to access an Iframe's content using javascript. I have been able to write code that does it. But every browser rejects it, not letting me gain access to the iframe's contents. Is there any way to get pass this issue?

function getContent(){
var myIFrame = document.getElementById('the-frame');
var content = myIFrame.contentWindow.document.body.innerHTML;

alert('content: ' + content);
}
2
  • Could you post your code here? Commented May 24, 2014 at 3:24
  • Do you own the content of the <iframe>? Frames are restricted by the same origin policy and crossing origins requires that the owners of the content give your origin permission. Commented May 24, 2014 at 3:45

2 Answers 2

3

Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.

None of the browsers would allowing accessing iframe which is from a different domain than your site. It is a serious security breach. Thus if you are loading iframe from different domain, no matter what you do, you can't access it.

You might not like the answer, but it is the fact.

Sign up to request clarification or add additional context in comments.

4 Comments

Is there any alternative for getting the any values from an iframe?
Unfortunately no u can never access iframe from other domain. But if u tell what u r trying to achieve there might be alternative
@user3552910 If you have access to the code on both sites you could implement something using postMessage > viget.com/extend/…
I'm trying to find the current source of an iframe as it changes
0

You could try something like this:

var iframe = document.getElementById("the-frame");
var iframe_content = iframe.contentDocument.body.innerHTML;

The variable iframe_content contains the contents (innerHTML) of the <body> tag of the iframe page.

1 Comment

no matter what method u use, it won't work if domain is different

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.