Skip to content

Instantly share code, notes, and snippets.

@olmokramer
Last active September 19, 2018 19:47
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 olmokramer/b4dd182a2e12be816a8344d98f854434 to your computer and use it in GitHub Desktop.
Save olmokramer/b4dd182a2e12be816a8344d98f854434 to your computer and use it in GitHub Desktop.
Rewrite/redirect URLs
// ==UserScript==
// @name url-rewriter
// @namespace https://github.com/olmokramer
// @description Rewrite current url or urls on the page
// @match *://*/*
// @run-at document-start
// @version 2
// @author Olmo Kramer
// ==/UserScript==
(function() {
'use strict';
function youtube2hooktube(url) {
url.host = 'hooktube.com';
if (url.pathname.slice(0, 7) == '/embed/') {
return url;
}
if (url.pathname.slice(0, 6) != '/watch') {
const vid_id = url.pathname.slice(1);
const search = url.search;
url.pathname = '/watch'
url.search = `?v=${vid_id}`;
if (search) {
url.search += `&${search.slice(1)}`;
}
}
return url;
}
function wikiwand2wikipedia(url) {
const [, lang, topic] = url.pathname.split('/');
if (lang) {
url.host = `${lang}.wikipedia.org`;
} else {
url.host = `en.wikipedia.org`;
}
if (topic) {
url.pathname = `/wiki/${topic}`;
if (url.hash) {
url.hash = url.hash.slice(2);
}
} else {
url.pathname = '';
}
return url;
}
const domains = {
'www.youtube.com': youtube2hooktube,
'youtu.be': youtube2hooktube,
'youtube-nocookie.com': youtube2hooktube,
'www.wikiwand.com': wikiwand2wikipedia,
};
const seen_urls = {};
function rewriteURL(url, transform) {
if (!(url in seen_urls)) {
seen_urls[url] = transform(new URL(url)).href;
}
return seen_urls[url];
}
function rewriteAttr(attr, domain, transform) {
const selector = `[${attr}*="${domain}"]`;
for (let el of document.querySelectorAll(selector)) {
const old_url = el.getAttribute(attr);
const new_url = rewriteURL(old_url, transform);
if (old_url != new_url) {
el.setAttribute(attr, rewriteURL(old_url, transform));
}
}
}
function rewriteURLs() {
for (let attr of ['href', 'src']) {
for (let [domain, transform] of Object.entries(domains)) {
rewriteAttr(attr, domain, transform);
}
}
}
if (window.location.host in domains) {
window.location.href = rewriteURL(window.location.href, domains[window.location.host]);
return;
}
document.addEventListener('DOMContentLoaded', function() {
new MutationObserver(function OnMutate() {
rewriteURLs(domains);
}).observe(document.body, {
attributes: true,
childList: true,
subtree: true,
});
rewriteURLs(domains);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment