Skip to content

Instantly share code, notes, and snippets.

@tellmeY18
Created October 23, 2024 03:52
Show Gist options
  • Select an option

  • Save tellmeY18/1fad6d8d18a1c7ce99929a52360155d9 to your computer and use it in GitHub Desktop.

Select an option

Save tellmeY18/1fad6d8d18a1c7ce99929a52360155d9 to your computer and use it in GitHub Desktop.
Cloudflare-Inject script for cloudflare inject
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// Fetch the original HTML response
const response = await fetch(request)
// If the response is a redirect, return it immediately without modification
if (response.redirected || response.status === 301 || response.status === 302) {
return response;
}
const contentType = response.headers.get("content-type") || "";
// Ensure it is an HTML response
if (contentType.includes("text/html")) {
// Retrieve the text
let html = await response.text();
// Inject the script before the closing head tag
html = html.replace(
"</head>",
`<script src="https://medispeak-app.pages.dev/assets/index.html.js" crossorigin="" type="module"></script>
<link rel="modulepreload" crossorigin="" href="https://medispeak-app.pages.dev/assets/App.js">
<link rel="stylesheet" href="https://medispeak-app.pages.dev/assets/App.css">
</head>`
);
html = html.replace(
"</body>",
`<div id="medispeak_root"></div></body>`
);
// Return the modified HTML as a new response
return new Response(html, {
headers: response.headers
})
}
// Return the original response if not HTML
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment