繁体   English   中英

Cloudflare Workers:如果 URL 包含参数,则注入代码

[英]Cloudflare Workers: Inject code if URL includes parameter

如果 URL 包含参数?beta ,我正在尝试使用 Cloudflare Workers 注入一些代码。

这是我试过的:

addEventListener("fetch", (event) => {
    event.respondWith(
        handleRequest(event.request).catch(
            (err) => new Response(err.stack, { status: 500 })
        )
    );
});

class ElementHandler {
    element(element) {
        element.append(`<style>.test {display:none}</style>`, { html: true });
    }
}

async function handleRequest(request) {

    const url = new URL(request.url)
    const res = await fetch(request)

    if (url.pathname.includes("?beta")) {
        return new HTMLRewriter().on("head", new ElementHandler()).transform(res)
    }
    else {
        return fetch(request)
    }
}

不幸的是,它不起作用......如果我添加?测试版到工人的 URL,代码不会添加到头部。

我没有从控制台收到任何错误。 谁能发现问题出在哪里?

他的问题在这里:

if (url.pathname.includes("?beta")) {

url.pathname仅包含 URL 的路径部分。但是, ? 并且它之后的所有内容都不被视为路径的一部分。 相反,它是url.search的一部分。 所以你可以这样做:

if (url.search.includes("?beta")) {

但是当有多个参数时,这可能会中断,比如?foo=bar&beta 相反,最好是使用url.searchParams ,它是所有参数的键/值 map:

if (url.searchParams.has("beta")) {

暂无
暂无

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

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