SponsorBlock/utils.js

41 lines
1.3 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) {
return await new Promise((resolve, reject) => {
setTimeout(() => {reject("TIMEOUT")}, timeout);
const interval = setInterval(() => {
let result = condition();
if (result !== false) {
resolve(result);
clearInterval(interval);
};
}, check);
});
}
2019-08-06 23:06:23 +02:00
function getYouTubeVideoID(url) {
//Attempt to parse url
let urlObject = null;
try {
urlObject = new URL(url);
2019-08-07 16:46:07 +02:00
} catch (e) {
console.error("[SB] Unable to parse URL: " + url);
return false;
2019-08-07 16:34:21 +02:00
}
//Check if valid hostname
if(!["www.youtube.com","www.youtube-nocookie.com"].includes(urlObject.host)) return false;
2019-08-07 16:34:21 +02:00
//Get ID from searchParam
if ((urlObject.pathname == "/watch" || urlObject.pathname == "/watch/") && urlObject.searchParams.has("v")) {
id = urlObject.searchParams.get("v");
2019-08-07 17:35:29 +02:00
return id.length == 11 ? id : false;
} else if (urlObject.pathname.startsWith("/embed/")) {
2019-08-07 17:35:29 +02:00
try {
return urlObject.pathname.substr(7, 11);
2019-08-07 17:35:29 +02:00
} catch (e) {
console.error("[SB] Video ID not valid for " + url);
return false;
2019-08-07 17:35:29 +02:00
}
2019-08-07 16:34:21 +02:00
}
2019-08-23 18:19:44 +02:00
return false;
}