MultiformeIngegno
MultiformeIngegno

Reputation: 7049

Cloudflare Workers: Inject code if URL includes parameter

I am trying to inject some code with Cloudflare Workers if the URL includes the parameter ?beta.

This is what I tried:

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)
    }
}

Unfortunately it doesn't work... the code is not added to the head if I add ?beta to the Worker's URL.

I don't get any errors from the console. Could anyone spot what's wrong?

Upvotes: 0

Views: 957

Answers (1)

Kenton Varda
Kenton Varda

Reputation: 45151

The problem his here:

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

url.pathname contains only the path part of the URL. However, the ? and everything after it is not considered part of the path. Instead, it is part of url.search. So you could do:

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

But this could break when there are multiple params, like ?foo=bar&beta. Instead, the best is to use url.searchParams, which is a key/value map of all the params:

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

Upvotes: 2

Related Questions