# This is the 1st commit message: fix: redirects + update root cdn url # This is the commit message #2: chore: workflow # This is the commit message #3: chore: naming
36 lines
No EOL
1.1 KiB
JavaScript
36 lines
No EOL
1.1 KiB
JavaScript
const ScriptName = '/js/script.js';
|
|
const Endpoint = '/api/event';
|
|
|
|
const ScriptWithoutExtension = ScriptName.replace('.js', '')
|
|
|
|
addEventListener('fetch', event => {
|
|
event.passThroughOnException();
|
|
event.respondWith(handleRequest(event));
|
|
})
|
|
|
|
async function handleRequest(event) {
|
|
const pathname = new URL(event.request.url).pathname
|
|
const [baseUri, ...extensions] = pathname.split('.')
|
|
|
|
if (baseUri.endsWith(ScriptWithoutExtension)) {
|
|
return getScript(event, extensions)
|
|
} else if (pathname.endsWith(Endpoint)) {
|
|
return postData(event)
|
|
}
|
|
return new Response(null, { status: 404 })
|
|
}
|
|
|
|
async function getScript(event, extensions) {
|
|
let response = await caches.default.match(event.request);
|
|
if (!response) {
|
|
response = await fetch("https://plausible.io/js/plausible." + extensions.join("."));
|
|
event.waitUntil(caches.default.put(event.request, response.clone()));
|
|
}
|
|
return response;
|
|
}
|
|
|
|
async function postData(event) {
|
|
const request = new Request(event.request);
|
|
request.headers.delete('cookie');
|
|
return await fetch("https://plausible.io/api/event", request);
|
|
} |