Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IFrame innerHTML using JavaScript

I'm trying to get an IFrame inner HTML using below code.

 <iframe src="http://www.msn.com" 
         width="100%" height="100%" marginwidth="0"
         scrolling="no" frameborder="0" id="divInfo" 
         onreadystatechange="MyFunction(this);"></iframe>   

JavaScript code is

  function MyFunction(frameObj)
    {
        if (frameObj.readyState == "complete")
        {
            alert(frameObj.document.body.innerHTML); 
        }
    }

But the alert shows me the html of current document. How can i get the inner HTML of iframe when the frmae ready state is complete.

If i use alert(frameObj.contentWindow.document.body.innerHTML); it gives me Access is denied error.

Thanks in advance.

like image 935
MUS Avatar asked Dec 21 '22 12:12

MUS


2 Answers

Access is denied error is caused by the same origin policy.

Since your page is hosted on http://www.example.com/ (For example), if you try to access details on http://www.msn.com/, the browser won't let you since they are from 2 different domains.

However, if you are trying to access data from the same domain - Hosting page: http://www.example.com/index.html, IFrame's page: http://www.example.com/iframe.html, then you should be able to get the content.

For more information on the Same Origin Policy, here's a link: http://en.wikipedia.org/wiki/Same_origin_policy

BTW, you may want to use frameObject.contentDocument instead

<script type="text/javascript">
function documentIsReady(frameObject) {
  alert(frameObject.contentDocument.body.innerHTML);
}
</script>

... and you can also use the onload instead of onreadystatechange...

<iframe src="iframe.html" onload="documentIsReady(this);"></iframe>
like image 83
DashK Avatar answered Dec 24 '22 02:12

DashK


You can't read the contents of an <iframe> that has content from a different domain than that of the parent page.

like image 25
Pointy Avatar answered Dec 24 '22 01:12

Pointy