Cache iframe request with ServiceWorker

2019-08-06 14:39发布

问题:

I'm trying to cache the request of an iframe with my ServiceWorker (using sw-toolbox.js).

But no matter what I try the files are never served from the ServiceWorker as Chrome Network Tab tells me.

Here is my service-worker.js:

'use strict';
importScripts('./build/sw-toolbox.js');

self.toolbox.options.cache = {
    name: 'ionic-cache'
};

var static_urls = [
    'https://quiqqer.local/test?app=1',
    'https://quiqqer.local/calendar?app=1'
];

self.toolbox.precache(static_urls);

self.toolbox.router.any('/(.*)', self.toolbox.cacheFirst, {origin: 'https://quiqqer.local'});

self.addEventListener('install', function (event)
{
    self.skipWaiting();
});

self.toolbox.router.default = self.toolbox.cacheFirst;

The self.toolbox.precache() function makes the requests to my static_urls properly, as I can see in the Network Tab.

But all the requests coming from the iframe (going to https://quiqqer.local/) seem to not being routed through the ServiceWorker.

What am I doing wrong? Or isn't it possible to cache the iframe requests?

Running on Chromium using Linux.

Thanks in advance

回答1:

There's probably an official HTML specification that provides a more canonical answer, but I'll just excerpt this from the MDN documentation:

The HTML element represents a nested browsing context, effectively embedding another HTML page into the current page. ... Each browsing context has its own session history and active document. The browsing context that contains the embedded content is called the parent browsing context.

You can think of what's going on in an <iframe>, including the request to load the <iframe>'s src itself, as being equivalent to what would happen if that <iframe> were loaded in a separate tab. Unless the service worker controlling the parent browsing context (i.e. your top-level page) also happens to include the <iframe>'s src under its scope, that service worker won't have any control over initially loading the <iframe> or the requests made from the <iframe>.