简体   繁体   English

Firefox服务工作者(作为代理)似乎可以工作,但是JS模块从未运行

[英]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://..." ). 以下代码应代理JS文件来修补导入,以便它们符合平台标准(即"./""../""/""http://..." )。

Works great in Chromium (67.0.3396.79 on Arch Linux). 在Chromium(Arch Linux上为67.0.3396.79)上运行良好。 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. 而且似乎在Firefox(Arch上的60.0.2(64位))上也能正常工作,至少从“网络”选项卡上,我可以看到所有已修补的源代码正在加载,但是由于某些原因,JS模块未运行。 Can't console.log etc. or anything. 不能console.log等。 Not sure how to get Firefox to bootstrap the application. 不确定如何使Firefox引导应用程序。

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 . 我注意到,获取标头全部是toLowerCase ed,但是我在这里阅读了一下 ,Mozilla还指出,标头名称在这里不区分大小写。

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)解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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