US-California

Hi,

How to Identify US-California in Worker Script

const countries = new Set([
  "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", 
  "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT",  "LU", 
  "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "GB"
])

You need to inspect the request.cf.regionCode object for the US state.

https://developers.cloudflare.com/workers/runtime-apis/request

2 Likes

Can you help in creating the right string and logic. I am new to the script.

I am trying to run quantcast choice script in EU and California

addEventListener('fetch', event => {
  event.passThroughOnException()
  event.respondWith(blockCountries(event.request))
})


const countries = new Set([
  "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", 
  "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT",  "LU", 
  "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "GB"
])

async function blockCountries(request) {
  // Get country value from request headers
  let country = request.headers.get('cf-ipcountry')

  // Find out if country is on the block list
  let countryBlocked = countries.has(country)

  // If it's on the blocked list, add a cookie banner
  if (countryBlocked){
    let response = await fetch(request)
    let body = await response.text()
    body = body.replace("</title>", "</title><script async src=\"https://www.example.com/quantcast.js\"></script>")
    return new Response(body, response)
  }

  // Catch-all return of the original response
  return await fetch(request)
}// JavaScript Document