external css file replace with workers

Hello awesome people, i have created a worker to replace external css. Here is my worker
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
const response = await fetch(request);
const contentType = response.headers.get('content-type') || '';

if (!contentType.includes('text/html')) {
return response;
}

let text = await response.text();
const baseUrl = new URL(request.url);

console.log('Base URL:', baseUrl.toString());

// Regex to match <link rel="stylesheet"> tags only
const stylesheetLinks = [...text.matchAll(/<link\s+([^>]*rel=["']stylesheet["'][^>]*)>/gi)];
console.log('Found stylesheet links:', stylesheetLinks.length);

for (const linkMatch of stylesheetLinks) {
const linkTag = linkMatch[0];
const hrefMatch = linkTag.match(/href=["']([^"']+)["']/);
if (hrefMatch) {
const href = hrefMatch[1];
const cssUrl = new URL(href, baseUrl).toString();
console.log('Fetching CSS from:', cssUrl);
try {
const cssResponse = await fetch(cssUrl);
if (cssResponse.ok) {
const cssText = await cssResponse.text();
const styleTag = `<style>${cssText}</style>`;
text = text.replace(linkTag, styleTag);
console.log('Replaced link tag with style tag.');
} else {
console.error(`Failed to fetch CSS from ${cssUrl}: HTTP ${cssResponse.status}`);
}
} catch (error) {
console.error(`Failed to fetch CSS from ${cssUrl}:`, error);
}
}
}

return new Response(text, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
});
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
const response = await fetch(request);
const contentType = response.headers.get('content-type') || '';

if (!contentType.includes('text/html')) {
return response;
}

let text = await response.text();
const baseUrl = new URL(request.url);

console.log('Base URL:', baseUrl.toString());

// Regex to match <link rel="stylesheet"> tags only
const stylesheetLinks = [...text.matchAll(/<link\s+([^>]*rel=["']stylesheet["'][^>]*)>/gi)];
console.log('Found stylesheet links:', stylesheetLinks.length);

for (const linkMatch of stylesheetLinks) {
const linkTag = linkMatch[0];
const hrefMatch = linkTag.match(/href=["']([^"']+)["']/);
if (hrefMatch) {
const href = hrefMatch[1];
const cssUrl = new URL(href, baseUrl).toString();
console.log('Fetching CSS from:', cssUrl);
try {
const cssResponse = await fetch(cssUrl);
if (cssResponse.ok) {
const cssText = await cssResponse.text();
const styleTag = `<style>${cssText}</style>`;
text = text.replace(linkTag, styleTag);
console.log('Replaced link tag with style tag.');
} else {
console.error(`Failed to fetch CSS from ${cssUrl}: HTTP ${cssResponse.status}`);
}
} catch (error) {
console.error(`Failed to fetch CSS from ${cssUrl}:`, error);
}
}
}

return new Response(text, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
});
}
Also i have added a trigger like this .example.com/ But it's not firing on website, firing on worker url. Any kind of help and direction would be highly appreciated
0 Replies
No replies yetBe the first to reply to this messageJoin