youtube-to-invidious/background.js

67 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2022-07-16 19:20:30 +00:00
let urlFromStorage
2022-07-15 13:46:52 +00:00
// Storage init
browser.runtime.onInstalled.addListener(function() {
browser.storage.sync.set({
url: "https://invidious.snopyta.org"
});
});
2022-07-16 19:20:30 +00:00
browser.storage.sync.onChanged.addListener(function(changes) {
if (changes.url && changes.url.newValue) {
urlFromStorage = changes.url.newValue
}
})
2022-07-15 13:46:52 +00:00
// 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;
}
2022-07-16 19:20:30 +00:00
function toInvidious(message) {
let url = message.url;
2022-07-15 13:46:52 +00:00
const name = message.targetName;
2022-07-16 19:20:30 +00:00
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"});
2022-07-15 13:46:52 +00:00
});