Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I traverse this element using iframe object and jQuery?

I'm trying to access a particular element (maybe more similar to this) using iframe object and jQuery but it isn't working.

The iframeWindow object is not null but the next statement doesn't seem working. I saw something like this on this answer but it doesn't work. Am I doing something wrong?

Here's my code:

RADIO.PHP

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="jquery.js"></script>
    <script>

        $(document).ready(function(){
            setTimeout(function(){
            var iframe= document.getElementById("iframe");
            var iframeWindow = iframe.contentWindow;
            var text=iframeWindow.$("div:nth-child(3) .c2").html();
            console.log(text);

            //DOESN'T PRINT "INNER MOST"

        }, 1000);

    });
    </script>
</head>
<body>
  <div class="c1">
  <iframe id="iframe" src="api.php" height="200" width="300">
  </iframe>
  </div>
</body>
</html>

API.PHP

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<script type="text/javascript" src="jquery.js"></script>
<body id="abody">
Hey
    <div class="c1"></div>
    <div class="c1">
        <p class="c2"></p>
    </div>
    <div class="c1">
        <p class="c2">
         INNER MOST
        </p>
    </div>
</body>
</html>

EDIT: I've corrected syntax mistakes.

like image 767
Shanky Avatar asked Jan 09 '17 09:01

Shanky


People also ask

Can you use jQuery in an iframe?

However, it's also possible to use a really simple jQuery to access the elements within the iFrame. Check it out below: $(document). ready(function(){ var iFrameDOM = $("iframe#frameID").

How do I view iframe content?

getIframeContent(frameId): It is used to get the object reference of an iframe. contentWindow: It is a property which returns the window object of the iframe. contentWindow. document: It returns the document object of iframe window.


1 Answers

You should use iframe.contentWindow.document instead of iframe.contentWindow in combination with find() and text() and it should work. Try this:

$(document).ready(function() {
  setTimeout(function() {
    var iframe = document.getElementById("iframe");
    var iframeWindow = iframe.contentWindow.document;
    var text = $(iframeWindow).find(".c1:nth-child(3) .c2").text();
    console.log(text);

    //PRINTS "INNER MOST"

  }, 1000);

});

As per MDN documentation says:

The contentWindow property returns the Window object of an iframe element. You can use this Window object to access the iframe's document and its internal DOM. This attribute is read-only, but its properties can be manipulated like the global Window object.

You can read more about iframe elements and how they work here.

like image 157
Ionut Avatar answered Oct 04 '22 07:10

Ionut