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?

2
  • 3
    You can't access a cross domain iframe due to "same origin policy". This is to protect from security exploits Commented Apr 21, 2018 at 12:37
  • take a look to the answer to this question Commented Apr 21, 2018 at 13:09

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, do you have an example of how I would implement this in my code?
@JohannesFlood Haven't I already given you a (very) simple example of how you may send and receive data between the iframe and the parent window?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.