【问题标题】:Is it possible to proxy iframe sub-resources with service workers?是否可以使用服务人员代理 iframe 子资源?
【发布时间】:2016-06-28 04:45:12
【问题描述】:

我有一个依赖第三方资源的 iframe。 iframe 本身没有 src,没有沙盒,通过 AJAX 填充内容,其子资源(例如 CSS、图像)存在于不同域的 CDN 上。

在发生中断的情况下,无论是我们的还是我们的客户,我都希望能够将 iframe 的 CSS 从我们的域切换到本地文件。我正在尝试通过我们的 Service Worker 中的 fetch 事件来做到这一点:

self.addEventListener('fetch', event => {
  const processEpubRequests = () => fetch(`/epubs/${event.request.url.split('epub-resource/')[1]}`);

  if(event.request.url.startsWith(`https://our_api.com`))
    event.respondWith(
      fetch(event.request)
        .then(response => response.status >= 400 ? processEpubRequests(response) : response)
        .catch(processEpubRequests)
    );
  else
    event.respondWith(
      caches.match(event.request)
        .then(response => response || fetch(event.request))
    );
});

这对于内容的 AJAX 请求非常有效,但 CSS 似乎不起作用。它以正确的响应显示在“网络”选项卡中,但就像 iframe 忽略它一样。

是否可以这样处理 iframe 子资源?

谢谢!

编辑: 我制作了一个 Github 页面演示来说明我所看到的。 页码:https://soluml.github.io/ServiceWorkerIframeExample/ 源:https://github.com/soluml/ServiceWorkerIframeExample/tree/gh-pages

【问题讨论】:

    标签: javascript iframe service-worker


    【解决方案1】:

    原来有一个Chrome bug out there for this issue。还有several related issues for Firefox

    但是,我们可以通过以下方式解决这个问题:

    1. 将 iframe 标签设置为同源虚拟 src。

    <iframe src=".iframe"></iframe>

    1. 在 Service Worker 中响应虚拟 src(如果我们使用的是虚拟 src 而不是实际的空白 html 文件)

    if(event.request.url == `${self.location.origin}/.iframe`)
      event.respondWith(
        new Response(`<!doctype html><title>i</title>`, {
          status: 200,
          headers: { "Content-Type": "text/html" }
        })
      );
    1. 不要使用contentDocument.write(),而是使用doc.documentElement.innerHTML。这将不会更改 iframe 中现有的 &lt;html&gt; 标记和 DOCTYPE。

    【讨论】:

      猜你喜欢
      • 2012-02-03
      • 2018-05-20
      • 1970-01-01
      • 2019-06-10
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      相关资源
      最近更新 更多