SponsorBlock/content.js

85 lines
2.5 KiB
JavaScript
Raw Normal View History

2019-07-09 20:50:19 +02:00
if(id = getYouTubeVideoID(document.URL)){ // Direct Links
sponsorsLookup(id);
2019-01-18 20:49:43 +01:00
}
2019-07-09 20:50:19 +02:00
//was sponsor data found when doing SponsorsLookup
var sponsorDataFound = false;
//the video
var v;
//the last time looked at (used to see if this time is in the interval)
var lastTime;
2019-01-18 20:49:43 +01:00
2019-01-18 20:59:34 +01:00
chrome.runtime.onMessage.addListener( // Detect URL Changes
2019-01-15 19:29:25 +01:00
function(request, sender, sendResponse) {
2019-01-18 21:20:50 +01:00
if (request.message === 'ytvideoid') { // Message from background script
2019-07-09 20:50:19 +02:00
sponsorsLookup(request.id);
2019-01-15 19:29:25 +01:00
}
//messages from popup script
if (request.message === 'sponsorStart') {
sponsorMessageStarted();
}
if (request.message === 'infoFound') {
sendResponse({
2019-07-09 20:50:19 +02:00
found: sponsorDataFound
})
}
2019-01-15 19:29:25 +01:00
});
2019-07-09 20:50:19 +02:00
function sponsorsLookup(id) {
2019-01-18 20:59:34 +01:00
v = document.querySelector('video') // Youtube video player
let xmlhttp = new XMLHttpRequest();
2019-07-09 20:50:19 +02:00
//check database for sponsor times
xmlhttp.open('GET', 'http://localhost/api/getVideoSponsorTimes?videoID=' + id, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
2019-07-09 20:50:19 +02:00
sponsorDataFound = true;
sponsorTimes = JSON.parse(xmlhttp.responseText).sponsorTimes;
2019-07-09 20:50:19 +02:00
// If the sponsor data exists, add the event to run on the videos "ontimeupdate"
v.ontimeupdate = function () {
sponsorCheck(sponsorTimes);
};
}
};
xmlhttp.send(null);
2018-06-23 16:06:18 +02:00
}
function sponsorCheck(sponsorTimes) { // Video skipping
//see if any sponsor start time was just passed
sponsorTimes.forEach(function (sponsorTime, index) { // Foreach Sponsor in video
//the sponsor time is in between these times, skip it
//if the time difference is more than 1 second, than the there was probably a skip in time,
// and it's not due to playback
if (Math.abs(v.currentTime - lastTime) < 1 && sponsorTime[0] >= lastTime && sponsorTime[0] <= v.currentTime) {
//skip it
v.currentTime = sponsorTime[1];
}
lastTime = v.currentTime;
});
}
2019-01-18 20:49:43 +01:00
2019-07-09 20:50:19 +02:00
function getYouTubeVideoID(url) { // Returns with video id else returns false
2019-01-18 20:49:43 +01:00
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
return (match && match[7].length == 11) ? match[7] : false;
}
function sponsorMessageStarted() {
let v = document.querySelector('video');
console.log(v.currentTime)
//send back current time
chrome.runtime.sendMessage({
message: "time",
time: v.currentTime
});
}