Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!