1

Is it possible for JavaScript to read the contents of an iframe embedded in the same page?

If it is, then the same-origin policy could be bypassed? I know of the XMLHttpRequest; it cannot be used to fetch data from other sites by the same-origin policy, e.g., an HTTP GET-request.

Reading the contents of an iframe would effectively provide the same functionality as (unrestricted) XMLHttpRequest’s fetching resources from arbitrary websites?

Shuzheng
  • 11,288
  • 20
  • 88
  • 186

1 Answers1

3

The short answer is, JavaScript can only look into an iframe from the same domain. So, no, you can't use an iframe get unrestricted cross domain access.

The longer answer is if you wanted to test this yourself, install a simple web server. It will take you < 2 mins. Here's a bunch

Edit your /etc/hosts file or C:\Windows\System32\Drivers\etc\hosts file and add

127.0.0.1  first.com
127.0.0.1  second.com

Make a folder with an index.html and an iframe.html. Put some JavaScript in index.html to try to look into iframe.html and also to include iframe.html as an iframe

<!-- index.html -->
<iframe src="http://second.com:8080/iframe.html></iframe>
<script>
   const iframe = document.querySelector('iframe');
   console.log(iframe.contentDocument.body.innerText);
</script>

<!-- iframe.html -->
<div>Hello world</div>

Run your server using that folder. In the browser go to http://second.com/8080:index.html

Open the devtools (chrome, firefox), look at the console, you should see

Hello World

This worked because they are both on the same domain.

Now change the URL in your browser to http://first.com:8080/index.html

This time you'll see something like

VM41:66 Uncaught DOMException: Failed to read the 'contentDocument' 
 property from 'HTMLIFrameElement': Blocked a frame with origin 
"http://first.com:8080" from accessing a cross-origin frame.
at HTMLIFrameElement.contentDocumentDesc.get [as contentDocument] 

Note: depending on which server you use you'll need to change 8080 above to match the port your server uses.

gman
  • 100,619
  • 31
  • 269
  • 393