Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

255
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda