代理站点以能够在 iframe 中进行所见即所得的编辑 - 它是如何工作的?

Proxying a site to be able to WYSIWYG edit in iframe - How does it work?

上下文

我想创建一个 WYSIWYG 编辑器,允许用户编辑在 iframe 中加载的第三方网站。我知道像 Optimizely 这样的公司使用代理来完成这个 (as described here),但我不太明白这是如何工作的。特别是这部分有点不清楚:

The Optimizely Editor loads http://www.mypage.com inside an iframe and uses window.postMessage to communicate with the page. This only works if that page already has a snippet like the one above on it. If that's not the case, the editor will timeout while waiting for a message from the iframe'd page, and will load it again via a proxy that actually inserts the snippet onto the page.

问题

代理究竟做了什么允许将 JS 片段插入页面并让用户编辑 iframe 中加载的其他不可编辑的内容?

鉴于:

  • Alice,有浏览器
  • Bob,经营一家提供编辑服务的网站
  • Carol,她经营着 Alice 想要编辑的网站

如果:

  1. Bob 向 Alice 发送了一个包含 iframe 的页面。
  2. iframe 告诉 Alice 的浏览器从 Carol 的站点加载页面

然后同源策略阻止 Bob 的客户端代码到达 Carol 的站点。

然而,当您使用代理时:

  1. Bob 向 Alice 发送了一个包含 iframe 的页面。
  2. iframe 告诉 Alice 的浏览器从 Bob 的站点加载页面。
  3. Bob 的站点通过以下方式响应页面请求:
    1. 正在从 Carol 的站点获取页面
    2. 正在修改
    3. 发送修改后的 HTML 作为对 Alice 浏览器请求的响应

现在 iframe 要么:

  • 与 Bob 页面的其余部分同源,因此同源策略不适用
  • 代理所做的修改(在步骤 3.2 中)允许通过 postMessage 进行跨域通信