简体   繁体   中英

Access iframe element and update it to the DOM

I want to access page2.html element containing img tag and update it to the page1.html img tag or replace img of page1.html to page2.html img. Both the files are on same domain so no need to worry about cross domain origin policy.

// Page1.html

   <body>

   <img id="someimage1" src="./captcha.asp"></img>
   <iframe src="page2.html"></iframe>
   <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
   <script type="text/javascript>
       var getImg = $('iframe').contents().find('#someimage2').html();
       $('#someimage1').replaceWith('<img>' getImg '</img>');
   </script>
   </body>

I get DOM Update as [object] [Object]

// Page2.html

   <body>

   <img id="someimage2" src="./captcha.asp"></img>
   <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

   </body>

I will help you with one Vanilla JS solution, you can modify it to JQuery:

First check if your IFrame contains any document at all

Firefox and Chrome Solution

var frame  = document.getElementById("frame");
if(frame.contentDocument) {
 // get the inner Document
 var innerDocument = frame.contentDocument;
 var img = innerDocument.getElementsByTagName("img")[0];
}

IE Solution

var frame  = document.getElementById("frame");
if(frame.contentDocument) {
 // get the inner Document
 var innerDocument = frame.contentWindow.document;
 var img = innerDocument.getElementsByTagName("img")[0];
}

When you got the image the rest is just a DOM manipulation operations.

Get Inner Document Body

var getIFrameCOntent = function(iFrame) {
  var frame = document.querySelector(iFrame);
  var innerDocument = frame.contentDocument || frame.contentWindow.document;

   var body = innerDocument.getElementsByTagName("body")[0];  

  return body;
}

Simple Solution

var frame = document.getElementById('frame').contentWindow.document.body;
    console.log(frame.getElementsByTagName("img")[0]);

try this code....

page1.html...
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
    <div id="imgAA">
    </div>
    <img src="img1.jpg" style="width:100px;" id="imgBB"/>
    <script>
            $(document).ready(function(){
                $("#imgAA").load("page2.html",function(data){
                    $("#imgBB").attr("src",$("#imgAA").find("img").attr("src"));
                });
            });
    </script>
</body>

page2.html...
<body>
   <img src="img2.jpg" style="width:50px;" id="img2"></img>
</body>

try this and tell me it is work fine....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM