Skip to content

Instantly share code, notes, and snippets.

Created January 17, 2022 22:04
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Cloudflare Worker script for customizing web search
// Cloudflare Worker script to automatically redirect search queries based on trigger words
addEventListener("fetch", event => {
// status code for redirect response; need something that won't cache
var statuscode = 303
// defining base URLs for search engines
var googleurl = ""
var ddgurl = ""
var duckyurl = "!+"
// if any of these words are in the query, show full search results
var filterwords = ["why","who","how","what","where","django","python","jquery","javascript","error", "etymology"]
// we only want to match these words, not substrings (e.g., don't match something like "howard")
var regex_string = "\\b(" + filterwords.join("|") + ")\\b"
async function handleRequest(request) {
// get the query from the page URL
const { searchParams } = new URL(request.url);
var query = searchParams.get('q');
// if the query contains any bangs, pass to DDG
if (new RegExp(/!([a-zA-Z]+)\b/).test(query)) {
var url = ddgurl + encodeURIComponent(query).replace(/%20/g,"+");
// if the query contains any filter words, pass it to Google
} else if (new RegExp(regex_string).test(query)) {
var url = googleurl + encodeURIComponent(query).replace(/%20/g,"+");;
// otherwise, pass the query to "I'm Feeling Ducky"
} else {
var url = duckyurl + encodeURIComponent(query).replace(/%20/g,"+");
// redirect to the correct URL
return Response.redirect(url, statuscode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment