SponsorBlock/utils.js

69 lines
2 KiB
JavaScript
Raw Normal View History

2019-08-20 18:46:05 +02:00
// Function that can be used to wait for a condition before returning
async function wait(condition, timeout = 5000, check = 100) {
2019-08-24 03:10:28 +02:00
return await new Promise((resolve, reject) => {
setTimeout(() => reject("TIMEOUT"), timeout);
let intervalCheck = () => {
let result = condition();
if (result !== false) {
resolve(result);
clearInterval(interval);
};
};
let interval = setInterval(intervalCheck, check);
//run the check once first, this speeds it up a lot
intervalCheck();
});
2019-08-20 18:46:05 +02:00
}
2019-08-06 23:06:23 +02:00
function getYouTubeVideoID(url) {
//Attempt to parse url
let urlObject = null;
try {
2019-08-24 03:10:28 +02:00
urlObject = new URL(url);
2019-08-07 16:46:07 +02:00
} catch (e) {
2019-08-24 03:10:28 +02:00
console.error("[SB] Unable to parse URL: " + url);
return false;
2019-08-07 16:34:21 +02:00
}
2019-08-24 03:10:28 +02:00
//Check if valid hostname
if(!["www.youtube.com","www.youtube-nocookie.com"].includes(urlObject.host)) return false;
2019-08-24 03:10:28 +02:00
//Get ID from searchParam
if ((urlObject.pathname == "/watch" || urlObject.pathname == "/watch/") && urlObject.searchParams.has("v")) {
2019-08-24 03:10:28 +02:00
id = urlObject.searchParams.get("v");
return id.length == 11 ? id : false;
} else if (urlObject.pathname.startsWith("/embed/")) {
2019-08-24 03:10:28 +02:00
try {
return urlObject.pathname.substr(7, 11);
} catch (e) {
console.error("[SB] Video ID not valid for " + url);
return false;
}
2019-08-07 16:34:21 +02:00
}
2019-08-23 18:19:44 +02:00
return false;
2019-08-24 19:06:25 +02:00
}
2019-08-24 19:59:53 +02:00
function localizeHtmlPage() {
2019-08-24 19:06:25 +02:00
//Localize by replacing __MSG_***__ meta tags
var objects = document.getElementsByClassName("popupBody")[0].children;
for (var j = 0; j < objects.length; j++) {
2019-08-24 19:06:25 +02:00
var obj = objects[j];
var valStrH = obj.innerHTML.toString();
var valNewH = valStrH.replace(/__MSG_(\w+)__/g, function(match, v1)
{
return v1 ? chrome.i18n.getMessage(v1) : "";
});
if(valNewH != valStrH)
{
obj.innerHTML = valNewH;
}
}
}
2019-08-24 03:10:28 +02:00