0

I'm working on a website which requires the user to sign in on a 3rd party website that's displayed on my website within an iframe. I'm trying to extract the html code of that website with jQuery but it doesn't really work. Here's my code.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Iframe</title>
<link rel="stylesheet" type="text/css" href="style.css">

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    console.log($("#iframe").contents().find("body"));
});

</script>
</head>

<body>
    <iframe src="https://www.google.com"></iframe>
</body>

</html>

I'm using google in my example but it's a different website I use. The result I'm getting is this - w.fn.init [prevObject: w.fn.init(0)] - but I can't find the html. Anyone who knows how to do this?

Johannes Flood
  • 625
  • 3
  • 7
  • 9
  • 3
    You can't access a cross domain iframe due to *"same origin policy"*. This is to protect from security exploits – charlietfl Apr 21 '18 at 12:37
  • take a look to the answer to this [question](https://stackoverflow.com/questions/22413098/how-to-use-cors-to-access-an-iframe) – gaetanoM Apr 21 '18 at 13:09

1 Answers1

1

Imagine your site being able to access the content of any iframe you're including. You could simply include websites like facebook, gmail or any banking site where a user is logged in and then steal their personal information. So this is strictly forbidden by default: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

There is an "opt-in" technique, though, where the communication between parent window and iframe is possible. Basically each site/document defines the information to be transmitted and sends it using the window.postMessage() method: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

So if a message is sent from one party

window.postMessage("hello!", "http://example.com");

it may be received by the other one

window.addEventListener("message", function(e) {
    console.log(e.data); // prints "hello!"
}, false); 
MattDiMu
  • 4,277
  • 1
  • 15
  • 24