使用javascript / jquery访问iframe的html

时间:2018-04-21 12:34:57

标签: javascript jquery html iframe

我正在开设一个网站,该网站要求用户在iframe中显示在我网站上的第三方网站上登录。我试图用jQuery提取该网站的HTML代码,但它并没有真正起作用。这是我的代码。

<!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>

我在我的示例中使用谷歌,但它是我使用的不同网站。我得到的结果是这个 - w.fn.init [prevObject:w.fn.init(0)] - 但我找不到html。谁知道怎么做?

1 个答案:

答案 0 :(得分:1)

想象一下,您的网站可以访问您所包含的任何iframe的内容。您可以简单地包含Facebook,gmail或用户登录的任何银行网站等网站,然后窃取他们的个人信息。因此,默认情况下严格禁止此操作:https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

但是,有一种“选择加入”技术,可以在父窗口和iframe之间进行通信。基本上每个站点/文档都定义了要传输的信息,并使用window.postMessage()方法发送它:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

因此,如果从一方发送消息

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

它可能被另一个接收

window.addEventListener("message", function(e) {
    console.log(e.data); // prints "hello!"
}, false);