Skip to content

Instantly share code, notes, and snippets.

@irazasyed
Last active September 30, 2019 14:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irazasyed/6554e37ecb79731c216d912190fc71e4 to your computer and use it in GitHub Desktop.
Save irazasyed/6554e37ecb79731c216d912190fc71e4 to your computer and use it in GitHub Desktop.
// Perform regex replacements and inject CSS/JavaScript with Cloudflare Workers
// https://community.cloudflare.com/t/perform-regex-replacements-and-inject-css-javascript-with-cloudflare-workers/90279
addEventListener('fetch', event => {
event.passThroughOnException()
event.respondWith(handleRequest(event.request))
})
/**
* Fetch and log a given request object
* @param {Request} request
*/
async function handleRequest(request) {
const response = await fetch(request)
var html = await response.text()
// Simple replacement regex
html = html.replace( /Source Phrase/g , 'Target Phrase')
// Inject scripts
const customScripts = '<style type="text/css">body{background:red}</style></body>'
html = html.replace( /<\/body>/ , customScripts)
// return modified response
return new Response(html, {
headers: response.headers
})
}
// Parse URL query strings with Cloudflare Workers
// https://community.cloudflare.com/t/parse-url-query-strings-with-cloudflare-workers/90286
addEventListener('fetch', event => {
event.passThroughOnException() // Optional; you know best
event.respondWith(handleRequest(event.request))
})
/**
* Fetch and log a given request object
* @param {Request} request
*/
async function handleRequest(request) {
const url = request.url
// Function to parse query strings
function getParameterByName(name) {
name = name.replace(/[\[\]]/g, '\\$&')
name = name.replace(/\//g, '')
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url)
if (!results) return null
else if (!results[2]) return ''
else if (results[2]) {
results[2] = results[2].replace(/\//g, '')
}
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
// Usage example
var test = getParameterByName('test')
console.log(test)
// Do your work
// ...
// Send on the response
const response = await fetch(request)
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment