Youtube to Invidious

Scan page for youtube embeds and urls and replace with Invidious.

Version vom 11.05.2019. Aktuellste Version

// ==UserScript==
// @name        Youtube to Invidious
// @author      OdinBrood
// @namespace   Krul & Brood
// @description Scan page for youtube embeds and urls and replace with Invidious.
// @include     *
// @exclude     /^http(s|)://(m\.|www\.|)youtube\.com/.*$/
// @exclude     /^http(s|)://(www\.|)invidio\.us/.*$/
// @exclude     /^http(s|)://(www\.|)invidious\.snopyta\.org/.*$/
// @exclude     /^http(s|)://(www\.|)vid.wxzm\.sx/.*$/
// @exclude     /^http(s|)://(www\.|)invidious\.kabi\.tk/.*$/
// @exclude     /^http(s|)://(www\.|)invidiou\.sh/.*$/
// @exclude     /^http(s|)://(www\.|)invidious\.enkirton\.net/.*$/
// @exclude     /^http(s|)://(www\.|)tube\.poal\.co/.*$/
// @version     5.2
// ==/UserScript==

var instance="invidio.us"; //set you favorite invidious instance! (https://github.com/omarroth/invidious/wiki/Invidious-Instances)

var a=1; //set to 0 to force autoplay off, set to 1 to keep embed's default
var b=1; //set to 1 to replace all youtube links to invidious
var c=0; //set to 1 to enable DASH playback (invidious beta feature)

var ytdomains=new RegExp(/^http(s|)\:\/\/(m\.|www\.|)youtu(|be|be-nocookie)\.(com|be)\/.*$/);
var emdlydomains=new RegExp(/^http(s|)\:\/\/cdn\.embedly\.com\/.*$/);
var filter=Array.filter;
var frames=filter(document.getElementsByTagName('iframe'),ytel);
if(frames.length>0)embed();
var observer=new MutationObserver(function(mutations){
  mutations.forEach(function(mutation){
    frames=filter(mutation.target.getElementsByTagName('iframe'),ytel);
    if(b==1)links=filter(mutation.target.getElementsByTagName('a'),ytel);
    if(frames.length>0)embed();
    if(links.length>0)link();
  });
});
observer.observe(document.body,{childList:true,subtree:true});

function embed(){
  for(var i=0;i<frames.length;i++){
    var url=new URL(frames[i].src);
    if(url.hostname.match(/embedly/)){
      var eurl=new URL(decodeURIComponent(url.searchParams.get('src')));
      url=eurl;
      frames[i].style.display=null;
      frames[i].removeAttribute("hidden");
      url.searchParams.set('autoplay',0);
    }
    url.hostname=instance;
    if(a==1){
      if(!url.searchParams.has('autoplay'))url.searchParams.set('autoplay',0);
    }else{
      url.searchParams.set('autoplay',0);
    }
    if(c==1)url.searchParams.set('quality','dash');
    url.searchParams.set('local',true);
    frames[i].src=url;
  }
}

function link(){
  for(var i=0;i<links.length;i++){
    var url=new URL(links[i].href);
    url.hostname=instance;
    url.searchParams.set('local',true);
    if(c==1)url.searchParams.set('quality','dash');
    links[i].href=url;
  }
}

function ytel(el){
  if(el.hasAttribute('src')&&(el.src.match(ytdomains)||el.src.match(emdlydomains))){
    return true;
  }else if(el.hasAttribute('href')&&el.href.match(ytdomains)){
    return true;
  }
  return false;
}