import getYouTubeID from 'get-youtube-id' import { MusemeOverlayAPI, MusemeSourceVideo, renderOverlay } from './overlay' import { allCheckboxes } from './userSettings' let loadingUserSettings: boolean = true let video: HTMLVideoElement let videoFound: boolean let videoLookupInterval: NodeJS.Timeout const getVideoId = (): string => { const url = window.location.href const videoId = getYouTubeID(url) return videoId } const isLive = () => { return false } let videoId = getVideoId() const checkVideoIdChange = () => { const currentVideoId = getVideoId() if (currentVideoId !== videoId) { dettach() if (currentVideoId) { videoId = currentVideoId tryAttach() } } } window.addEventListener('popstate', (event) => { videoId = getVideoId() dettach() tryAttach() }) setInterval(() => { checkVideoIdChange() }, 1000) const loadEnabled = async () => { chrome.storage.sync.get(allCheckboxes, (result) => { for (const checkboxKey of allCheckboxes) { overlayApi.setSetting(checkboxKey, result[checkboxKey] ?? true) } loadingUserSettings = false if (!dettach) { tryAttach() } }) } loadEnabled() const lookup = async () => { video = document.querySelector('.video-stream.html5-main-video') videoFound = !!video tryAttach() } const attach = (videoId: string) => { const abstractVideo: MusemeSourceVideo = { play: function (): void { video.play() }, pause: function (): void { video.pause() }, getCurrentTime: function (): number { return video.currentTime }, getRect: function (): { width: number height: number top: number left: number } { return video.getBoundingClientRect() }, isPaused: function (): boolean { return video.paused }, addEventListener: function ( event: string, callback: (event: Event) => void ): void { video.addEventListener(event, callback) }, removeEventListener: function ( event: string, callback: (event: Event) => void ): void { video.addEventListener(event, callback) }, } const live = isLive() return renderOverlay(abstractVideo, videoId, {}, live) } let dettach: () => void let overlayApi: MusemeOverlayAPI const tryAttach = () => { if (videoFound) { ;[overlayApi, dettach] = attach(videoId) loadEnabled() } } const main = () => { lookup() if (!videoFound) { videoLookupInterval = setInterval(() => { if (!videoFound) { lookup() } if (videoFound) { clearInterval(videoLookupInterval) } }, 1000) } } main() chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { const { type, data } = request // console.log('onMessage', request) overlayApi.setSetting(type, data) })