Skip to content

Instantly share code, notes, and snippets.

@olmokramer
Last active September 19, 2018 19:47
Show Gist options
  • 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 YouTube2HookTube
// @namespace https://github.com/olmokramer
// @description Automatically redirect YouTube to HookTube
// @include *
// @run-at document-start
// @version 4
// @author Olmo Kramer
// ==/UserScript==
(function() {
'use strict';
const seen_urls = {};
function rewriteURL(url) {
if (url in seen_urls) {
return seen_urls[url];
}
url = new URL(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 seen_urls[url] = url.href;
}
if (window.location.host.match(/youtu(\.be|be\.com)/)) {
window.location.href = rewriteURL(window.location);
return;
}
function replaceURLs() {
const domains = [
'youtube.com',
'youtu.be',
'youtube-nocookie.com',
];
const attrs = ['href', 'src'];
for (let domain of domains) {
for (let attr of attrs) {
for (let el of document.querySelectorAll(`[${attr}*="${domain}"]`)) {
const old_url = el.getAttribute(attr);
const new_url = rewriteURL(old_url);
if (new_url != old_url) {
el.setAttribute(attr, rewriteURL(el.getAttribute(attr)));
}
}
}
}
}
document.addEventListener('DOMContentLoaded', function() {
new MutationObserver(replaceURLs).observe(document.body, {
attributes: true,
childList: true,
subtree: true,
});
replaceURLs();
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment