简体   繁体   中英

Firefox service worker (as proxy) seems to work, but JS modules never run

I'm playing around with service workers. The following code should proxy JS files to patch the imports so that they conform to platform standards (ie, "./" , "../" , "/" , or "http://..." ).

Works great in Chromium (67.0.3396.79 on Arch Linux). And seems to work just as well in Firefox (60.0.2 (64-bit) on Arch), at least from the network tab, I can see all of the patched sources loading, but for some reason the JS modules aren't running. Can't console.log etc. or anything. Not sure how to get Firefox to bootstrap the application.

I noticed that the fetch headers are all toLowerCase ed, but I read up on that here and Mozilla also points out that header names are case-insensitive here .

I also thought maybe because the content-length was possibly changed that the file wasn't being received completely, but I didn't see any parse errors and indeed the network tab had the correct content-length changes, so I ruled that out.

const maybeAppendJS = (x) =>
    x.endsWith(".js")
        ? x
        : `${x}.js`;


const maybePatchURL = (x) =>
    x.match(/(^'@.*'(.)?$)|(^"@.*"(.)?$)/)
        ? `"/node_modules/${maybeAppendJS(eval(x))}";`
        : x;


const maybePatchImport = (x) =>
    x.startsWith("import ")
        ? x.split(/\s/).map(maybePatchURL).join(" ")
        : x;


async function maybeRewriteImportStatements(event) {

    let candidate = event.request.url;
    const url = maybeAppendJS(candidate);

    const resp = await fetch(url);

    if (!resp.headers.get("content-type").startsWith("text")) {
        const text = await resp.text();
        const newText = text.split(/\n/g)
            .map(maybePatchImport)
            .join("\n");

        return new Response(newText, {headers: resp.headers});
    }

    if (resp.headers.get("content-type").startsWith("text/")) {
        const location = `${url.substring(0, url.length - 3)}/index.js`;
        return new Response(null, {status: 302, headers: {location: location}});
    }

    console.log("Service worker should never get here");

}

this.addEventListener('fetch', (event) => {
    if (event.request.destination === "script" || event.request.referrer.endsWith(".js") || event.request.url.endsWith(".js")) {
        event.respondWith(maybeRewriteImportStatements(event));
    }
});

已通过每晚升级到Firefox(62.0a1.20180611-1)解决此问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM