0

I am building an extension that gets the total time for a youtube playlist. It can get the video element of the playlist but cannot query each video element to get the time as it returns a null element but the same code works fine in chrome console.

The function in question is the getTime() and the line is timeStringElement = video.querySelector('span#text');

function getTime(){
    let videos = document.querySelectorAll('#playlist-items');
    videos[videos.length-1].scrollIntoView(true);
    let timeHours = 0;
    let timeStringElement;
    let containerElement;
    for (let video of videos){
        timeStringElement = video.querySelector('span#text');
        if (timeStringElement !== null){
            console.log(timeStringElement.innerText);
            timeHours += getHours(timeStringElement.innerText);
        }
    }
    return timeHours;
}
function getHours(time){
    let timeList = time.split(':').reverse();
    let timeHours = 0.0;
    let multiplier = 1/3600;
    for (let timeValue of timeList){
        timeHours += timeValue*multiplier;
        multiplier *= 60;
    }
    return timeHours;
}

window.onload = function(){
    let url = window.location.href;
    if (url.indexOf('list=') !== -1){
        let hours = getTime();
        console.log(hours);
    }
}
  • See [How to detect page navigation on YouTube and modify its appearance seamlessly?](https://stackoverflow.com/q/34077641) – wOxxOm Jul 30 '21 at 10:06
  • thanks but that appears to work 5yrs ago but the id 's and classes have changed – Issac Abraham Jul 30 '21 at 10:19
  • unfortunately, it still doesn't work. I don't understand the issue when printing the video element, its in there but I cannot query it to get the timestamp – Issac Abraham Jul 30 '21 at 10:30
  • Ah, it's a different problem then: `getTime()` is added by the page so you need to call it in [page context](/a/9517879). – wOxxOm Jul 30 '21 at 10:54
  • thanks for helping with that issue. now I am facing the original issue where the script runs once but when I navigate it doesn't reload the script. The solution before doesn't work as I think youtube has changed. Is there any way to check if youtube has changed history and then reinject the script – Issac Abraham Jul 30 '21 at 13:53
  • See [this answer](https://stackoverflow.com/questions/2844565/is-there-a-javascript-jquery-dom-change-listener/39508954). – wOxxOm Jul 30 '21 at 14:51

0 Answers0