Home > Back-end >  Change the current YouTube video time without using YouTube API
Change the current YouTube video time without using YouTube API

Time:11-12

I am writing a Chrome extension (that does NOT use the YouTube Player API for iframe Embeds), in which I want to add the functionality to skip to a certain timestamp in a YouTube Video. So, I would have a time-stamp in the HH:MM:SS format, and clicking on it would make the video time "seek" to that timestamp. I found one answer here that uses the following code:

document.getElementById("movie_player").seekTo(seconds,true);

However, whenever I try to inject this code via a content script, I get this error:

Error in event handler: TypeError: document.getElementById(...).seekTo is not a function

I'll share my code as well for clarification. First, the popup.js:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {message: scroll_time}, null);
});

where scroll_time is a string representing the timestamp of the video. In the contentScript file is the following code:

var sec = parseInt(request.message);
document.getElementById("movie_player").seekTo(sec, true);

I've also tried the following code in the popup.js file:

chrome.tabs.query({active: true, currentWindow: true}, tabs => {
    chrome.scripting.executeScript({
            target: {tabId: tabs[0].id},
            files: ['scrollVideo.js'],
    }, ()=>{
            chrome.tabs.sendMessage(tabs[0].id,{scrollTo: scroll_time});
    });
});

with the following code in a separate file:

chrome.runtime.onMessage.addListener(message=>{
    if (message.scrollTo) {
        scrollVid(message.scrollTo);
    };
});

function scrollVid(time) {
    var sec = parseInt(time);
    document.getElementById("movie_player").seekTo(sec, true);
};

In both methods, I get the error described above. I wish to avoid using the YouTube Player API for iframe Embeds, where the seekTo function is described. Is there any way of accomplishing this without the API, or is using it the only way? Please help me out, as this is the final thing I want my extension to be able to do.

CodePudding user response:

I've tried this in an youtube window and it worked:

document.getElementsByTagName('video')[0].currentTime = 20

I'm not sure if this covers everything that you need or if it will work as expected but hope it does :)

  • Related