Reputation: 181
I need obtain the iframe body after iframe load
Upvotes: 13
Views: 29826
Reputation: 531
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>
Upvotes: 0
Reputation: 9235
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.
Upvotes: 1
Reputation: 32112
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.
Upvotes: 20