Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

256
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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")) {
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda