【问题标题】:Change the current YouTube video time without using YouTube API在不使用 YouTube API 的情况下更改当前 YouTube 视频时间
【发布时间】:2021-12-23 10:44:56
【问题描述】:

我正在编写一个 Chrome 扩展程序(不使用 iframe 嵌入的 YouTube 播放器 API),我想在其中添加功能以跳到 YouTube 视频中的某个时间戳。所以,我会有一个 HH:MM:SS 格式的时间戳,点击它会使视频时间“搜索”到那个时间戳。我找到了一个答案here,它使用以下代码:

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

但是,每当我尝试通过内容脚本注入此代码时,我都会收到此错误:

事件处理程序中的错误:TypeError: document.getElementById(...).seekTo 不是函数

为了澄清,我也会分享我的代码。一、popup.js:

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

其中 scroll_time 是表示视频时间戳的字符串。在 contentScript 文件中是以下代码:

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

我还在 popup.js 文件中尝试了以下代码:

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});
    });
});

在单独的文件中使用以下代码:

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);
};

在这两种方法中,我都会收到上述错误。我希望避免使用描述 seekTo 函数的YouTube Player API for iframe Embeds。有没有任何方法可以在没有 API 的情况下完成此操作,或者是使用它的唯一方法?请帮帮我,因为这是我希望我的扩展程序能够做的最后一件事。

【问题讨论】:

标签: javascript google-chrome google-chrome-extension youtube youtube-api


【解决方案1】:

我已经在一个 youtube 窗口中尝试过,它成功了:

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

我不确定这是否涵盖了您需要的所有内容,或者它是否会按预期工作,但希望可以:)

【讨论】:

  • 谢谢,这也适用于扩展程序。
猜你喜欢
  • 2011-07-10
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 2011-12-10
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多