youtube-to-invidious/background.js
2022-07-16 21:20:30 +02:00

67 lines
1.4 KiB
JavaScript

let urlFromStorage
// Storage init
browser.runtime.onInstalled.addListener(function() {
browser.storage.sync.set({
url: "https://invidious.snopyta.org"
});
});
browser.storage.sync.onChanged.addListener(function(changes) {
if (changes.url && changes.url.newValue) {
urlFromStorage = changes.url.newValue
}
})
// Url format
function getVideoToken(url) {
// https://regexr.com/531i0
var rx = /(?:\/|%3D|v=|vi=)([0-9A-z-_]{11})(?:[%#?&]|$)/g;
var arr = rx.exec(url);
return arr[1];
}
function cleanToken(token) {
let t = token;
// https://regexr.com/531i0
t = t.replace(/^(vi=|v=)/,"");
t = t.replace(/^(\/)/,"");
t = t.replace(/^(%3D)/,"");
t = t.replace(/(&|%)$/,"");
return t;
}
function toInvidious(message) {
let url = message.url;
const name = message.targetName;
const subst = urlFromStorage + `/watch?v=`;
let token = getVideoToken(url)
const cleanedToken = cleanToken(token)
url = url.replace(/.*\/watch\?v=/gm, subst);
if (name != "_self") {
browser.tabs.create(
{active: true, url: url}
);
} else {
browser.tabs.update(
{url: url, loadReplace: false}
)
}
console.log('Youtube to invidious is redirecting you to invidious')
}
// Links click event handling
browser.runtime.onMessage.addListener(function(message) {
toInvidious(message)
});
// Page action
browser.pageAction.onClicked.addListener(function(page) {
toInvidious({url: page.url, targetName: "_self"});
});