getCurrentTime() for YouTube Video

前端 未结 4 1001
故里飘歌
故里飘歌 2021-02-14 17:02

I\'m writing a Chrome Extension in Javascript and I want to get the current time for the playing video on youtube.com. I tried using the answer from question Getting Current You

4条回答
  •  被撕碎了的回忆
    2021-02-14 17:12

    As Ben correctly assumed, you're executing the code in the context of your background page, which is wrong.

    To interact with other pages, you need to inject a content script in them. See overview of that here. You'll probably need to learn how Messaging works so you can gather data in a content script and communicate it to the background page.

    To make a minimal example, you can have a file inject.js

    // WARNING: This example is out of date
    // For the current HTML5 player, see other answers' code snippets
    ytplayer = document.getElementById("movie_player");
    ytplayer.getCurrentTime();
    

    And in your background page script, you can inject that into the current page as follows (when the button is clicked, for instance)

    chrome.browserAction.onClicked.addListener(function(tab) {
      chrome.tabs.executeScript({
        file: 'inject.js'
      });
    });
    

    Then, you'll see the result of the execution in the console of the currently open page. To report the result back, you'll need to use chrome.runtime.sendMessage

提交回复
热议问题