bandito40
bandito40

Reputation: 637

Extract links from iframe - Javascript

I am trying to extract the links in from a page loaded into Iframe that is not of the same origin as the main web page. The javascript console for FF and Chromium doesn't report any errors. Both browsers also do not extract the links from the webpage in the iframe.

HTTP/1.0 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Origin
X-Frame-Options: ALLOW-FROM https://example.com/
Content-Type: text/html; charset=UTF-8


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
 <iframe name='iframe' id='iframe' src="https://www.example.com"></iframe>

 <script>
  var a = document.getElementById('iframe')
  var links = a.getElementsByTagName('a');

  document.write(links.length);
  for(i=0; i<links.length; i++) {
    document.write(links[i].href);
  } 
</script>
<div id="results">results</div>

Upvotes: 0

Views: 724

Answers (1)

brunnerh
brunnerh

Reputation: 184554

Cannot be done because security.

You don't get errors because you query on the iframe element and not its contentDocument.

<iframe name='iframe' id='iframe' src="https://www.example.com"></iframe>

<script>
  var a = document.getElementById('iframe');
  var links = a.contentDocument.getElementsByTagName('a');
</script>

Upvotes: 2

Related Questions