【问题标题】:Accessing the html of an iframe with javascript/jquery使用 javascript/jquery 访问 iframe 的 html
【发布时间】:2018-04-22 03:52:32
【问题描述】:

我正在开发一个网站,该网站要求用户登录第三方网站,该网站在 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>

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

【问题讨论】:

  • 由于“同源策略”,您无法访问跨域 iframe。这是为了防止安全漏洞
  • 看看这个question的答案

标签: javascript jquery html iframe


【解决方案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); 

【讨论】:

  • 谢谢,你有我如何在我的代码中实现它的例子吗?
  • @JohannesFlood 我不是已经给了你一个(非常)简单的例子,说明如何在 iframe 和父窗口之间发送和接收数据吗?
猜你喜欢
  • 2014-03-23
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 2012-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多