Summary Files Commits Branches @commit @diff @stats
path: root / youtube-invidious-video-redirector.js
blob: 03bf689aa163cde62df51a67e0b0dc47905b43fe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// ==UserScript==
// @name        YouTube to Invidious video redirector
// @description When opening YouTube videos, redirect to an Invidious instance, but when going back from instance, don't redirect again
//
// @version     1.1
// @license     MIT
// @author      Syndamia
//
// @source      https://gitlab.com/Syndamia/userscripts/-/blob/main/youtube-invidious-video-redirector.js
// @supportURL  https://gitlab.com/Syndamia/userscripts/-/issues
// @homepage    https://gitlab.com/Syndamia/userscripts/
// @icon        https://upload.wikimedia.org/wikipedia/commons/a/a0/Invidious-logo.svg
//
// @namespace   Syndamia
// @match       *://www.youtube.com/*
// @run-at      document-start
// ==/UserScript==

const invidiousInstance = 'yewtu.be';



const ytdObserver = new MutationObserver(function(mutations) {
    // Detect when ytd-app element is present
    if (document.getElementsByTagName('ytd-app').length > 0) {
        // Attach the redirection function to it
        const observer = new MutationObserver(redirect);
        observer.observe(document.getElementsByTagName('ytd-app')[0], { childList: true, attributes: true, subtree: true, });
        ytdObserver.disconnect();
    }
});

ytdObserver.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});

// Opening YouTube links in YouTube doesn't reload the page, but we know that if the page changes, ytd-app (element that contains the UI) will also change
// so, when ytd-app changes, we check if the link has changed, and redirect
function redirect() {
    const latest = localStorage.getItem('LATEST'), loc = window.location.search.substr(3);

    if (loc !== latest) {
        localStorage.removeItem(latest);
        localStorage.removeItem('LATEST');
    }

    if (window.location.pathname === '/' || localStorage.getItem(loc) === 'true') {
        return;
    }

    localStorage.setItem(loc, true);
    localStorage.setItem('LATEST', loc);
    window.location.host = invidiousInstance;
}