# jQuery Code to Get HTML Content of IFrame$("#myButton"). on('click', function() { alert($("#myIframe"). contents(). find("html").
getElementById('myIFrame'); // Let's say that you want to access a button with the ID `'myButton'`, // you can access via the following code: const buttonInIFrame = iFrame. contentWindow. document. getElementById('myButton'); // If you need to call a function in the iframe, you can call it as follows: iFrame.
On this page, two iframes interact with each other using JavaScript. First we show how one iframe can get references to the other iframe and the document inside it. Then we provide an example which demonstrates one iframe accessing and modifying the other's properties, objects, and content.
You have to use the contents()
method:
$("#myiframe").contents().find("#myContent")
Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/
API Doc: https://api.jquery.com/contents/
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(function() {
//here you have the control over the body of the iframe document
var iBody = $("#iView").contents().find("body");
//here you have the control over any element (#myContent)
var myContent = iBody.find("#myContent");
});
</script>
</head>
<body>
<iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>
If iframe's source is an external domain, browsers will hide the iframe contents (Same Origin Policy). A workaround is saving the external contents in a file, for example (in PHP):
<?php
$contents = file_get_contents($external_url);
$res = file_put_contents($filename, $contents);
?>
then, get the new file content (string) and parse it to html, for example (in jquery):
$.get(file_url, function(string){
var html = $.parseHTML(string);
var contents = $(html).contents();
},'html');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With