Sync media

You can set the start timet to syncronize the media.

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name        Sync media
// @description You can set the start timet to syncronize the media.
// @namespace   utubo/syncmedia
// @match       https://www.youtube.com/*
// @match       https://abema.tv/*
// @version     1.0
// @author      -
// @name:ja     Sync media
// @description:ja You can set the start timet to syncronize the media.
// ==/UserScript==

(function() {
  // ----------
  // sync
  const INTERVAL = 5000;
  const RANGE = 1;
  let timer = null;
  let startDateTime = null;
  const syncVideo = () => {
    if (!startDateTime) return;
    clearTimeout(timer);
    timer = setTimeout(syncVideo, INTERVAL);
    let target = null;
    if (location.host === 'abema.tv') {
      target = document.querySelector('video[preload=metadata]');
    } else {
      target = document.querySelector('video');
    }
    if (!target) return;
    const syncTime = (Date.now() - startDateTime) / 1000;
    if (Math.abs(target.currentTime - syncTime) > RANGE) {
      target.currentTime = syncTime;
    }
  };

  // ----------
  // ui
  const msecToStr = msec => {
    const tzoffset = (new Date()).getTimezoneOffset() * 60000;
    return new Date(msec - tzoffset)
      .toISOString()
      .replace('T', ' ')
      .replace(/\.\d\d\dZ$/, '');
  };

  const showDlg = () => {
    const val = prompt('⏱Set the start time', msecToStr(startDateTime || Date.now()));
    if (val === null) return;
    startDateTime = new Date(val).getTime();
    syncVideo();
  };

  addEventListener('keydown', e => {
    if (e.altKey && e.key === 's') {
      showDlg();
    }
  });

})();