Created
March 26, 2024 23:08
-
-
Save AndreaHasani/7ebab79394290ffbf3d362a4e76315f8 to your computer and use it in GitHub Desktop.
Google-search-url-redirect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @license GPL-2.0-only | |
!function() { | |
"use strict"; | |
let rules = [ | |
{ | |
matchRegex: RegExp(/^(?:.*?(?:\/RU=|&q=|&as=))?https?:\/\/((?!test)[a-z]+)\.?m?\.wikipedia\.org\/(?:[a-z]+|wiki)\/(?!Special:Search)(.*?)(?:$|\/RK=.*|&sa=.*)/), | |
replaceWith: "https://www.wikiwand.com/$1/$2" | |
}, | |
{ | |
matchRegex: RegExp(/^(?:.*?(?:\/RU=|&q=|&as=))?https?:\/\/(?:old|www)\.reddit\.com\/((?:r|u)\/.*?)(?:$|\/RK=.*|&sa=.*)/), | |
replaceWith: "https://old.reddit.com/$1" | |
} | |
]; | |
let searchEngine = { | |
hosts: ["google.com"], | |
resultContainerSelectors: ["div.GyAeWb#rcnt", "div.mJxzWe"] | |
}; | |
const modifyUrls = (observer, resultContainer, options) => { | |
try { | |
rules.forEach(rule => { | |
let linkSelector = rule.selector || ""; | |
let links = document.querySelectorAll(linkSelector); | |
links.forEach(link => { | |
let url = decodeURIComponent(link.href); | |
if (rule.matchRegex.test(url)) { | |
let modifiedUrl = url.replace(rule.matchRegex, rule.replaceWith); | |
link.href = modifiedUrl; | |
} | |
}); | |
}); | |
observer.observe(resultContainer, { childList: true, subtree: true }); | |
} catch (error) { | |
console.error("URL Modification Error: ", error); | |
} | |
}; | |
try { | |
let currentHost = window.location.host; | |
if (searchEngine.hosts.some(host => currentHost.includes(host))) { | |
let resultContainers = searchEngine.resultContainerSelectors || ["body"]; | |
resultContainers.forEach(selector => { | |
let resultContainer = document.querySelector(selector); | |
if (resultContainer) { | |
let observer = new MutationObserver(mutations => modifyUrls(observer, resultContainer, searchEngine)); | |
observer.observe(resultContainer, { childList: true, subtree: true }); | |
modifyUrls(observer, resultContainer, searchEngine); | |
} | |
}); | |
} | |
} catch (error) { | |
console.error("Error executing URL Modifier Script: ", error); | |
} | |
}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment