Help with Workers to deliver cached pages for UTM tags

Hi,

I’m trying to use the worker below to strip query strings from the URL, deliver the cached page, then re-attach the query strings to the URL.

I found the code below here on the forum but I’m not sure it works correctly in my case.
Google Analytics had some issues with the incoming adwords traffic in some cases which doesn’t happend when the worker is disabled.

Can you please confirm that the code bellow attaches the strings back to the URL after it delivers the cached page?
By looking at the code I’m not sure it does.

Thanks.

urlRegex = new RegExp('^(label|refreshce|gclid|cx|ie|cof|siteurl|zanpid|origin|utm_[a-z]+|hsa_[a-z]+|fbid|fbclid|mr:[A-z]+|ref(id|src))$');


addEventListener('fetch', event => {
    event.passThroughOnException()
    event.respondWith(handleRequest(event.request))
})
  
  
async function handleRequest(request) {
    
    let url = new URL(request.url)
    
    url = await normalizeUrl(url)
    
    let modifiedRequest = new Request(url, request)
  
console.log(modifiedRequest.url)

    return fetch(modifiedRequest)
}

async function normalizeUrl(url) {
    let deleteKeys = []
    
    for(var key of url.searchParams.keys()) { 
        if(key.match(urlRegex)){
            deleteKeys.push(key)
        }
    }

    deleteKeys.map(k => url.searchParams.delete(k))
    return url
}
2 Likes

Hi @catalin.oanca
I am thinking of doing something similar. Did you ever resolve this issue with Google Analytics?

Also - to check if your worker attaches the strings back to the URL after it delivers the cached page, can’t you just load the page with all query strings in your browser and see if the address bar shows the query strings? GA would get the parameters from your local browsing session.

You can try a page rule

*example.com/*?utm=*

cache level: ignore query string

deleteKeys.map(k => url.searchParams.delete(k))

What does k means here?

I am afraid that really is a question rather for Newest 'javascript' Questions - Stack Overflow