Skip to content

Instantly share code, notes, and snippets.

@eidam
Last active August 26, 2021 06:58
Show Gist options
  • Save eidam/5d636bdc130b62a449ec7f22d635db42 to your computer and use it in GitHub Desktop.
Save eidam/5d636bdc130b62a449ec7f22d635db42 to your computer and use it in GitHub Desktop.
A simple Cloudflare Worker that demonstrates using HTMLRewriter to change 3rd party site (Polywork page)
// This script is running on https://eidam.dev
// change dnsWithPolyworkCustomDomainCname to your CNAME record set to provided record by Polywork
// note: you cannot use Polywork record directly
const dnsWithPolyworkCustomDomainCname = "polywork-origin.eidam.dev"
// change link to your list of links
const links = [
{link: "https://github.com/eidam", name: "🍴 https://github.com/eidam"},
{link: "https://twitter.com/adam_janis", name: "🐤 https://twitter.com/adam_janis"},
{link: "https://statusflare.com", name: "📈 https://statusflare.com"},
]
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
/**
* @param {Request} request
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
const { pathname } = new URL(request.url)
// fetch Polywork HTML
let res = await fetch(request, {
// resolve override to custom domain CNAME
// and cache Polywork response for 2 hours
cf: {
resolveOverride: dnsWithPolyworkCustomDomainCname,
cacheTtl: 3600 * 2,
}
})
// run HTMLRewriter for index responses
// and replace introduction block with custom list
// or return cached Polywork response for the rest of pages
return pathname == "/" ?
new HTMLRewriter()
.on("#profile-introduction-panel .text-size-introduction", {
element(element) {
element.replace(`
<div class="text-muted text-size-introduction">
<ul>
${links.map(link => {
return `<li><a href="${link.link}" target="_blank" rel="noopener">${link.name}</a></li>`
}).join("\n")}
</ul>
<a href="/eidam/expanded">
<h5 class="d-inline text-dark">Read more</h5>
</a>
</div>
`, {html: true})
},
})
.transform(res)
: res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment