jiten2015
jiten2015

Reputation: 197

Parsing a website's HTML tags in <iframe>

Is it possible to parse tags in a html webpage which is shown in an iframe? I have tried to compile the code as follows, but it doesn't work.

       <!DOCTYPE html>
       <html>
       <body>

       <iframe id="Frame" src="Url"></iframe>

       <button onclick="myFunction()">Parse it</button>

      <p id="demo"></p>

      <script>
      function myFunction() {
      var x = document.getElementById("Frame").src.getElementByTagName("title");
     document.getElementById("demo").innerHTML = x;
     }
     </script>

     </body>
     </html>

Upvotes: 2

Views: 6363

Answers (1)

Larry Lane
Larry Lane

Reputation: 2191

You can do something like the following. Just remember to change the src of your iframe to the url of the page you are actually loading:

<!DOCTYPE html>
<html>
<body>


<iframe id="Frame" src="sample.html"></iframe>

<button onclick="myFunction()">Parse it</button>

<p id="demo"></p>

<script>

function myFunction() {

var x;         

//get the iframe object
var iframe = document.getElementById('Frame');

//cross browser solution to get the iframe document
//of the iframe
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

     //if the document is not undefined
     if (iframeDocument) {

       //do something with the frames dom

       //get the content of the title tag from the iframe
       x = iframeDocument.getElementsByTagName("title")[0].innerHTML;

        }    

              document.getElementById("demo").innerHTML = x;    

}

</script>

</body>
</html>

Note: This solution will not work on websites that do not allow cross origin loading in iframes. If you were to add the url http://www.google.com to the src of the iframe for example it would display the following error in the developer console.

Load denied by X-Frame-Options: https://www.google.com/?gws_rd=ssl does not permit cross-origin framing.

This is another error you may receive for the same reason. I recieved this error by trying it on by own website(bytewarestudios.com).

Error: Permission denied to access property "document"

Upvotes: 4

Related Questions