Can you create two asyncs in one

Can you create two asyncs in one cloudflare worker? Im trying to apply custom CSS & apply a cookie under a condition but the required responses are different. Not sure how to merge these together
20 Replies
kian
kian2y ago
We can just use a thread
Retard
RetardOP2y ago
Hey Kian. So check this out I currently have this script running on all urls of my website
Retard
RetardOP2y ago
Pastebin
addEventListener('fetch', event => { event.passThroughOnExceptio...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Retard
RetardOP2y ago
However, I would also like to run this on all urls of my website
Retard
RetardOP2y ago
Pastebin
/* Attempting to Incorporate Additional Styling as Well */async fun...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Retard
RetardOP2y ago
And I am simply struggling to merge these two scripts together In short Script 1 performs a few different actions depending on some If statements Script 2 changes custom CSS IF country is NOT US or Canada @kiannh
kian
kian2y ago
https://developers.cloudflare.com/workers/runtime-apis/html-rewriter/#element is likely a more performant (and better) way of adding content at the end of the <body> element - other than that, it just sounds like a clean-up of the if statements and adding the code into a single Worker
Retard
RetardOP2y ago
We have so many projects going on here I can push code to cloudflare for testing purposes as needed
kian
kian2y ago
class ScriptHandler {
element(element) {
if (element.tagName === "body") {
const html =
'<style type="text/css">.postid-46227 .pewc-total-field-wrapper, .postid-46501 .pewc-total-field-wrapper, .price,.price-wrapper,.single_add_to_cart_button,.quantity,#welcome-notice, .wcct_custom_text_wrap, .wcct_countdown_timer_wrap, .badge-container, .wcct_custom_text_wrap, .wcct_timer_wrap, #hide-catalog, #wcpay-payment-request-wrapper, #wcpay-payment-request-button-separator, #menu-item-64460, #menu-item-64457, .message__container locale--US {display: block!important} #show-catalog {visibility: hidden!important;}#pewc-per-product-label, #pewc-per-product-total, #pewc-grand-total-label, #pewc-grand-total, #pewc-group-64059, #pewc-group-64060, #price-match {display: inline!important;} .header-bottom, #menu-item-76425, #menu-item-76493 {display:none;} </style>';
element.append(html, { html: true });
}
}
}

class StyleHandler {
element(element) {
if (element.tagName === "body") {
const html = ".header_logo{display:none!important}";
element.append(html, { html: true });
}
}
}

export default {
async fetch(req, env, ctx) {
ctx.passThroughOnException();

const cookies = req.headers.get("Cookie") || "";
const country = req.cf.country;

const northAmerica = country == "US" || country == "CA"

let response = await fetch(req);
response = new Response(response.body, response);

if (
!northAmerica &&
!cookies.includes("pricing-mode=on")
) {
response.headers.set(
"Set-Cookie",
"pricing-mode=on;max-age=604800;Path=/"
);
return response;
}

const url = new URL(req.url);

if (
url.search.includes("gclid") ||
url.search.includes("bing") ||
url.search.includes("fbclid") ||
url.pathname.includes("pricing")
) {
response.headers.set(
"Set-Cookie",
"pricing-mode=on;max-age=604800;Path=/"
);
return response;
}

let html = new HTMLRewriter();
if (!northAmerica) {
html.on("body", new StyleHandler());
}

if (cookies.includes("pricing-mode=on")) {
const contentType = response.headers.get("Content-Type") || "";
if (!contentType.startsWith("text/html")) {
return response;
}

html.on("body", new ScriptHandler());
}

return html.transform(response);
},
};
class ScriptHandler {
element(element) {
if (element.tagName === "body") {
const html =
'<style type="text/css">.postid-46227 .pewc-total-field-wrapper, .postid-46501 .pewc-total-field-wrapper, .price,.price-wrapper,.single_add_to_cart_button,.quantity,#welcome-notice, .wcct_custom_text_wrap, .wcct_countdown_timer_wrap, .badge-container, .wcct_custom_text_wrap, .wcct_timer_wrap, #hide-catalog, #wcpay-payment-request-wrapper, #wcpay-payment-request-button-separator, #menu-item-64460, #menu-item-64457, .message__container locale--US {display: block!important} #show-catalog {visibility: hidden!important;}#pewc-per-product-label, #pewc-per-product-total, #pewc-grand-total-label, #pewc-grand-total, #pewc-group-64059, #pewc-group-64060, #price-match {display: inline!important;} .header-bottom, #menu-item-76425, #menu-item-76493 {display:none;} </style>';
element.append(html, { html: true });
}
}
}

class StyleHandler {
element(element) {
if (element.tagName === "body") {
const html = ".header_logo{display:none!important}";
element.append(html, { html: true });
}
}
}

export default {
async fetch(req, env, ctx) {
ctx.passThroughOnException();

const cookies = req.headers.get("Cookie") || "";
const country = req.cf.country;

const northAmerica = country == "US" || country == "CA"

let response = await fetch(req);
response = new Response(response.body, response);

if (
!northAmerica &&
!cookies.includes("pricing-mode=on")
) {
response.headers.set(
"Set-Cookie",
"pricing-mode=on;max-age=604800;Path=/"
);
return response;
}

const url = new URL(req.url);

if (
url.search.includes("gclid") ||
url.search.includes("bing") ||
url.search.includes("fbclid") ||
url.pathname.includes("pricing")
) {
response.headers.set(
"Set-Cookie",
"pricing-mode=on;max-age=604800;Path=/"
);
return response;
}

let html = new HTMLRewriter();
if (!northAmerica) {
html.on("body", new StyleHandler());
}

if (cookies.includes("pricing-mode=on")) {
const contentType = response.headers.get("Content-Type") || "";
if (!contentType.startsWith("text/html")) {
return response;
}

html.on("body", new ScriptHandler());
}

return html.transform(response);
},
};
try this might not work, might have got some if statements the wrong way around needs cleaning up but as a concept, probably works
Retard
RetardOP2y ago
This code has been deployed if you would like to see how it works life. In the AM, I will also proceed with some testing, study this a bit, and let you know! If there is anything I can do to help your community, reviews, shoutouts, post some of my code I have written, I would love to return the favor Or, I can boost the server?
Retard
RetardOP2y ago
Retard
RetardOP2y ago
Updates When not connected to VPN, International CSS is hidden
Retard
RetardOP2y ago
Retard
RetardOP2y ago
When connected to international VPN, International CSS is visible
Retard
RetardOP2y ago
Retard
RetardOP2y ago
Great news! However the syling is not actually applying on the frontend - for instance the entire website should be dark mode - I am checking this now
Retard
RetardOP2y ago
Looks like styling code is appearing outside of <style></style>
Retard
RetardOP2y ago
Resolved @kiannh, just forgot the <style type="text/css">etc</style> on the second StyleHandler @kiannh, I would like to commission (unpaid) your support one more time My Cache System (Cloudflare & WP-Rocket) are breaking my script at the plugin level to auto redirect based on visitor navigator.language In other words, right when I clear my cache, and you visit ellasbubbles.com from a french device you will be redirected to ellasbubbles.com/fr However, after about 2+ minutes when cache collects, this redirect stops working So I am attempting to build a redirect at the Cloudflare Worker level to handle this and avoid cache issues The URL format is: ellasbubbles.com + 2 letter language code + subdirectories I am working on this now, but you might be able to help me much more efficiently
Retard
RetardOP2y ago
Cloudflare Community
HTTP Language and worker redirect
How can I use worker to redirect based on browser language something like this RewriteCond %{HTTP:Accept-Language} ^ar [NC] RewriteRule ^$ /ar/ [L,R=301]
Retard
RetardOP2y ago
I have started building this out in Dynamic/Redirect rules but this is going to get quite lengthy
Want results from more Discord servers?
Add your server