首页 > 解决方案 > 浏览 YouTube 视频时检测 Chrome 扩展程序

问题描述

我有一个 Chrome 扩展程序,可以记录视频在 YouTube 上播放的时间。它获取视频开始播放的开始时间和视频暂停的结束时间,然后显示秒数。但是,如果用户在播放视频时离开页面,我怎么能得到秒数呢?

清单.json:

{
  "manifest_version": 2,
  "name": "TimeTracker",
  "version": "1.0",
  "background": {
   "scripts": ["background.js"]
 },
  "permissions": [
    "*://www.youtube.com/*",
    "webNavigation",
    "tabs"
  ]
}

背景.js:

chrome.webNavigation.onHistoryStateUpdated.addListener(function (details) {
  // If the URL after navigation is the video URL, execute timetracker.js
  if (details.url.includes('watch?')) {
    chrome.tabs.executeScript(null,{file:'timetracker.js'});
  }
});

timetracker.js:

function findVideo(callback) {
  var getVideo = setInterval(function() {
    var video = document.querySelector('.html5-video-player video');
    if (video != null) {
      clearInterval(getVideo);
      callback(video);
    }
  }, 50)
}

function trackPlayTime(video) {
  var start = 0;
  var end = 0;

  // Get the start UTC after video starts playing
  video.onplaying = function() {
      start = Date.now();
  };

  // Get the end UTC after video is paused, alert start and end, reset variables
  video.onpause = function() {
      end = Date.now();
      var seconds = (end - start) / 1000;
      alert(`Seconds: ${seconds}`);
      start = 0;
      end = 0;
  };
}

findVideo(trackPlayTime);

标签: javascriptgoogle-chrome-extensionyoutube

解决方案


推荐阅读