Skip to content

Instantly share code, notes, and snippets.

@npilk
Created January 17, 2022 22:04
Show Gist options
  • Save npilk/6a9077d183eb799b16537e1ee90f8673 to your computer and use it in GitHub Desktop.
Save npilk/6a9077d183eb799b16537e1ee90f8673 to your computer and use it in GitHub Desktop.
Cloudflare Worker script for customizing web search
// Cloudflare Worker script to automatically redirect search queries based on trigger words
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
// status code for redirect response; need something that won't cache
var statuscode = 303
// defining base URLs for search engines
var googleurl = "https://www.google.com/search?q="
var ddgurl = "https://www.duckduckgo.com/html/?q="
var duckyurl = "https://www.duckduckgo.com/html/?q=!+"
// 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