我正在撰寫一個 Chrome 擴展程式(不使用 iframe 嵌入的 YouTube 播放器 API),我想在其中添加跳到 YouTube 視頻中某個時間戳的功能。所以,我會有一個 HH:MM:SS 格式的時間戳,點擊它會使視頻時間“尋找”到那個時間戳。我在這里找到了一個使用以下代碼的答案:
document.getElementById("movie_player").seekTo(seconds,true);
但是,每當我嘗試通過內容腳本注入此代碼時,都會出現此錯誤:
事件處理程式中的錯誤:TypeError: document.getElementById(...).seekTo is not a function
我也會分享我的代碼以供澄清。首先,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);
};
在這兩種方法中,我都收到了上述錯誤。我希望避免將YouTube Player API 用于 iframe Embeds ,其中描述了 seekTo 函式。有沒有辦法在沒有 API 的情況下實作這一點,或者是使用它的唯一方法?請幫幫我,因為這是我希望我的擴展程式能夠做的最后一件事。
uj5u.com熱心網友回復:
我在 youtube 視窗中嘗試過這個,它有效:
document.getElementsByTagName('video')[0].currentTime = 20
我不確定這是否涵蓋了您需要的所有內容,或者它是否會按預期作業,但希望它能:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/357768.html
標籤:javascript 谷歌浏览器 谷歌浏览器扩展 YouTube youtube-api
下一篇:VS2019除錯chrome黑屏
