I need obtain the iframe body after iframe load
-
3i need you to be more concise. – RPM1984 Nov 10 '10 at 22:52
-
1You cant get anything from that iframe if the document is located in another domain. – Dr.Molle Nov 10 '10 at 23:43
3 Answers
document.getElementById('frame').contentDocument.body
will give you it in pure JavaScript, assuming that the iframe's ID is frame
. In jQuery, that would be $('#frame').contents().find('body')
.
Note that because of the same-origin policy, this will only work if the iframe and the surrounding pages' URLs have exactly the same hostname and port number.
Edit: You commented that you get an "Access denied" error when you tried this code. The same-origin policy is why this happens. The excellent Browser Security Handbook has information about this. A close reading of that web page will suggest that there are ways to break through, though this is not possible unless you control the enclosed site because of security and privacy reasons.

- 31,641
- 6
- 68
- 95
-
The iframe src it's located in another server and the (iFrame.contentDocument) return a error "Permission denied" or "Access denied" – user207123 Nov 10 '10 at 23:26
Because of security reasons there is no way to get iframe content with javascript if it is on different domain. Take a look at JSONP instead.

- 9,107
- 12
- 59
- 85
After much searching the jQuery solution was actually pretty simple, so thought I'd save the 30 minute headache for others as I went through all sorts of code and functions trying to find something.
You can actually access functions & variables in the parent document using parent.
so you literally just need to add an event listener to the iframe onload to run parent.function();
Keep in mind the iframe doesn't have the javascript files loaded that the parent has (ie. no jQuery, no momentJS etc.) so running the function on the parent is a great method in my case.
<script>
function afterLoading(){
$('#messageLog').html('TIMESTAMP ---'+'>'+$('#displayWindow').contents().find("body").html()+'\n'+$('#messageLog').html());
}
$('#displayWindow').on('load', function(){
parent.afterLoading();
});
//below this is the complete code, the above 2 functions is how it works
setInterval("printQueue()",10000);
function printQueue(){
$('#displayWindow').attr("src","");
$('#displayWindow').attr("src","http://127.0.0.1/test.php");
}
</script>
<div class="col-xl-4">
<textarea id="messageLog" style="width:100%;height:100%;"></textarea>
</div>
<div class="col-xl-4">
<iframe id="displayWindow" style="width:100%;height:100%;"></iframe>
</div>

- 451
- 4
- 5