From 30e94d1d6f2d15fdfdcd15cf199b781b19fe9745 Mon Sep 17 00:00:00 2001 From: TC Date: Thu, 3 Jun 2021 21:45:28 +0200 Subject: [PATCH] Refactor videoElement getter into a provider with callback --- plugins/disable-autoplay/front.js | 31 ++++++++----------------------- providers/video-element.js | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 23 deletions(-) create mode 100644 providers/video-element.js diff --git a/plugins/disable-autoplay/front.js b/plugins/disable-autoplay/front.js index c40eb7fd..eb1b72db 100644 --- a/plugins/disable-autoplay/front.js +++ b/plugins/disable-autoplay/front.js @@ -1,25 +1,10 @@ -let videoElement = null; +const { ontimeupdate } = require("../../providers/video-element"); -const observer = new MutationObserver((mutations, observer) => { - if (!videoElement) { - videoElement = document.querySelector("video"); - } - - if (videoElement) { - videoElement.ontimeupdate = () => { - if (videoElement.currentTime === 0 && videoElement.duration !== NaN) { - // auto-confirm-when-paused plugin can interfere here if not disabled! - videoElement.pause(); - } - }; - } -}); - -function observeVideoElement() { - observer.observe(document, { - childList: true, - subtree: true, +module.exports = () => { + ontimeupdate((videoElement) => { + if (videoElement.currentTime === 0 && videoElement.duration !== NaN) { + // auto-confirm-when-paused plugin can interfere here if not disabled! + videoElement.pause(); + } }); -} - -module.exports = observeVideoElement; +}; diff --git a/providers/video-element.js b/providers/video-element.js new file mode 100644 index 00000000..7be61c89 --- /dev/null +++ b/providers/video-element.js @@ -0,0 +1,22 @@ +let videoElement = null; + +module.exports.ontimeupdate = (cb) => { + const observer = new MutationObserver((mutations, observer) => { + if (!videoElement) { + videoElement = document.querySelector("video"); + if (videoElement) { + observer.disconnect(); + videoElement.ontimeupdate = () => cb(videoElement); + } + } + }); + + if (!videoElement) { + observer.observe(document, { + childList: true, + subtree: true, + }); + } else { + videoElement.ontimeupdate = () => cb(videoElement); + } +};