Adding second function to current worker script

Hi,

Okay, I don’t know much js, so I’m struggling with how to do this.

I currently have a worker that searches/replaces certain text on my page based on time.

I’d like to add some js to bypass the cache when I user is logged in to my wp site.

When I just add the second script below the original, the original gets wonky, the time is off, it stops working.

I’m wondering if I can only have one eventlistener maybe?

Here are my scripts, original first, how would I combine them? Or should I be doing this another way?

Thanks, Chris

//original
//worker script replaces Author's ad ID and data ad slot
//with CP's when less than 19 seconds in current minute

addEventListener("fetch", event => {
  event.respondWith(fetchAndReplace(event.request))
})

async function fetchAndReplace(request) {
  // Fetch from origin server.
  let response = await fetch(request)

  // Make sure we only modify text, not images.
  let type = response.headers.get("Content-Type") || ""
  if (!type.startsWith("text/")) {
    // Not text. Don't modify.
    return response
  }

  // Read response body.
  let text = await response.text()

  //get current seconds
    var d = new Date();
    var r = d.toUTCString();
    var n = d.getSeconds();

   //if less than 19, it belongs to CP
   if (n < 19){

  //to display CP ad ownership and count
   var AdsChk= r+" | CP"; 

  //set up replacement
    var AdR = text.replace(/js\?client=(.*?)"/gi, "js?client=pub-13873641xxxxxxx\"").replace(/ad-client="(.*?)"/gi, "ad-client=\"pub-13873641xxxxxxx\"").replace(/slot="(.*?)"/gi, "slot=\"21879xxxxx\"").replace(/AdsChk/g, AdsChk);
}

   //else this is author's hit
   else { 
  //to display ad ownership and count
   var AdsChk= r+" | A";

     //set up replacement to show ad ownership, no change in ads
    var AdR = text.replace(/AdsChk/g, AdsChk);

}

   //run replacement
   let modified = AdR

    // Return modified response.
  return new Response(modified, {
    status: response.status,
    statusText: response.statusText,
    headers: response.headers
  })
}
//---------need to add-----------------------
//bypass cache if user logged in
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event))
})

async function handleRequest(event) {
  let request = event.request;
  let response = null;
  cookies = request.headers.get("Cookie");
  if (cookies && cookies.toLowerCase().includes("wordpress_")){
    console.log("We have cookies. Don't cache.", cookies);
    response = await fetch(request);
    response = new Response(response.body, response);
    response.headers.set("x-cfw-cache", "BYPASS");
    return response;
  }
  let cache = caches.default;
  response = await cache.match(request);
  if (response && response.status !== 200){
    response = null;
  }
  if (!response){
    console.log("No cache. Will fetch.");
    response = await fetch(request);
    response = new Response(response.body, response);
    let responsecookies = response.headers.get("Set-Cookie");
    if (responsecookies && responsecookies.toLowerCase().includes("wordpress_")){
      //Wordpress auth/test cookies are being set here. We don't want to cache.
      response.headers.set("x-cfw-cache", "NO");
    } else {
      
      response.headers.delete("Set-Cookie"); //Cloudflare won't cache responses containing Set-Cookie.
      response.headers.set("x-cfw-cache", "MISS");
      if (response.status == 200){
        event.waitUntil(cache.put(request, response.clone()));
      }
    }
  } else {
    response = new Response(response.body, response);
    response.headers.set("x-cfw-cache", "HIT");
  }
  
  return response
}
//end script

Hi,

You’d increase your chances of reaching the right eyeballs if you edit your original post to set the category to Developers > Workers.

thank you -

1 Like