Add a check for the presence of video elements that may have been missed when observing…
- User
Add a check for the presence of video elements that may have been missed when observing mutations.
js - Assistant
Add a check for the presence of video elements that may have been missed when observing mutations.
import "requestidlecallback-polyfill";
import { EventImpl } from "./EventImpl.js";
import debug from "./debug.js";
const adKeywords = new Set([
"advertise",
"promo",
"sponsor",
"banner",
"commercial",
"preroll",
"midroll",
"postroll",
"ad-container",
"sponsored",
]);
const adKeywordsRegex = (() => {
const pattern = Array.from(adKeywords).join("|");
return new RegExp(pattern, "i");
})();
const filterVideoNodes = (nodes) => {
const result = [];
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node instanceof HTMLVideoElement) {
result.push(node);
} else if (node instanceof HTMLElement) {
const videos = node.querySelectorAll("video");
for (let j = 0; j < videos.length; j++) {
result.push(videos[j]);
}
} else if (node.shadowRoot) {
const shadowVideos = node.shadowRoot.querySelectorAll("video");
for (let k = 0; k < shadowVideos.length; k++) {
result.push(shadowVideos[k]);
}
}
}
return result;
};
const isAdVideo = (video) => {
if (
adKeywordsRegex.test(video.className) ||
adKeywordsRegex.test(video.title)
)
return true;
let parent = video.parentElement;
while (parent) {
if (
adKeywordsRegex.test(parent.className) ||
adKeywordsRegex.test(parent.id)
)
return true;
parent = parent.parentElement;
}
return false;
};
const isMutedVideo = (video) => {
return (
video.hasAttribute("muted") &&
!video.classList.contains("vjs-tech") &&
!video.preload
);
};
const isVideoReady = (video) => video.readyState >= 3;
const waitForVideoReady = (video, callback) => {
const checkVideoState = () => {
if (isVideoReady(video)) {
callback(video);
} else {
requestAnimationFrame(checkVideoState);
}
};
checkVideoState();
};
export class VideoObserver {
constructor() {
this.videoCache = new Set();
this.onVideoAdded = new EventImpl();
this.onVideoRemoved = new EventImpl();
this.observer = new MutationObserver(this.handleMutations);
this.intersectionObserver = new IntersectionObserver(
this.handleIntersections,
{ threshold: 0.1 },
);
}
handleMutations = (mutationsList) => {
window.requestIdleCallback(
() => {
for (let i = 0; i < mutationsList.length; i++) {
const mutation = mutationsList[i];
if (mutation.type !== "childList") continue;
const addedVideos = filterVideoNodes(mutation.addedNodes);
for (let j = 0; j < addedVideos.length; j++) {
this.checkAndHandleVideo(addedVideos[j]);
}
const removedVideos = filterVideoNodes(mutation.removedNodes);
for (let k = 0; k < removedVideos.length; k++) {
this.handleVideoRemoved(removedVideos[k]);
}
}
},
{ timeout: 1000 },
);
};
handleIntersections = (entries) => {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if (entry.isIntersecting) {
this.handleIntersectingVideo(entry.target);
}
}
};
enable() {
this.observer.observe(document, { childList: true, subtree: true });
const videos = this.getAllVideoEls();
for (let i = 0; i < videos.length; i++) {
this.checkAndHandleVideo(videos[i]);
}
}
disable() {
this.observer.disconnect();
this.intersectionObserver.disconnect();
}
getAllVideoEls() {
const videos = document.querySelectorAll("video");
if (videos.length) return Array.from(videos);
// Use it only if we don't find videos
// It takes a long time to complete
const videoElements = new Set();
const traverseShadowRoot = (root) => {
if (!root) return;
const shadowVideos = root.querySelectorAll("video");
for (let i = 0; i < shadowVideos.length; i++) {
videoElements.add(shadowVideos[i]);
}
const shadowElements = root.querySelectorAll("*");
for (let i = 0; i < shadowElements.length; i++) {
if (shadowElements[i].shadowRoot)
traverseShadowRoot(shadowElements[i].shadowRoot);
}
};
const allElements = document.querySelectorAll("*");
for (let i = 0; i < allElements.length; i++) {
if (allElements[i].shadowRoot)
traverseShadowRoot(allElements[i].shadowRoot);
}
return Array.from(videoElements);
}
checkAndHandleVideo = (video) => {
if (this.videoCache.has(video)) return;
this.videoCache.add(video);
this.intersectionObserver.observe(video);
};
handleIntersectingVideo = (video) => {
this.intersectionObserver.unobserve(video);
if (isAdVideo(video) || isMutedVideo(video)) {
debug.log("The promotional/muted video was ignored", video);
return;
}
waitForVideoReady(video, this.handleVideoAdded);
};
handleVideoAdded = (video) => {
this.onVideoAdded.dispatch(video);
};
handleVideoRemoved = (video) => {
if (!document.contains(video)) {
this.videoCache.delete(video);
this.onVideoRemoved.dispatch(video);
}
};
}
To ensure that all video elements are detected—including those that might be missed by the MutationObserver—you can implement an additional check that periodically scans the DOM for any new video elements that haven't been processed yet. This can be achieved by introducing a periodic scan using requestIdleCallback, which efficiently schedules the scan during the browser's idle periods without impacting performance.
Here's how you can enhance your existing VideoObserver class to include this additional check:
scanForMissedVideos method that retrieves all video elements and processes any that are not already in the videoCache.Below is the updated code with the necessary modifications:
import "requestidlecallback-polyfill";
import { EventImpl } from "./EventImpl.js";
import debug from "./debug.js";
const adKeywords = new Set([
"advertise",
"promo",
"sponsor",
"banner",
"commercial",
"preroll",
"midroll",
"postroll",
"ad-container",
"sponsored",
]);
const adKeywordsRegex = (() => {
const pattern = Array.from(adKeywords).join("|");
return new RegExp(pattern, "i");
})();
const filterVideoNodes = (nodes) => {
const result = [];
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node instanceof HTMLVideoElement) {
result.push(node);
} else if (node instanceof HTMLElement) {
const videos = node.querySelectorAll("video");
for (let j = 0; j < videos.length; j++) {
result.push(videos[j]);
}
} else if (node.shadowRoot) {
const shadowVideos = node.shadowRoot.querySelectorAll("video");
for (let k = 0; k < shadowVideos.length; k++) {
result.push(shadowVideos[k]);
}
}
}
return result;
};
const isAdVideo = (video) => {
if (
adKeywordsRegex.test(video.className) ||
adKeywordsRegex.test(video.title)
)
return true;
let parent = video.parentElement;
while (parent) {
if (
adKeywordsRegex.test(parent.className) ||
adKeywordsRegex.test(parent.id)
)
return true;
parent = parent.parentElement;
}
return false;
};
const isMutedVideo = (video) => {
return (
video.hasAttribute("muted") &&
!video.classList.contains("vjs-tech") &&
!video.preload
);
};
const isVideoReady = (video) => video.readyState >= 3;
const waitForVideoReady = (video, callback) => {
const checkVideoState = () => {
if (isVideoReady(video)) {
callback(video);
} else {
requestAnimationFrame(checkVideoState);
}
};
checkVideoState();
};
export class VideoObserver {
constructor() {
this.videoCache = new Set();
this.onVideoAdded = new EventImpl();
this.onVideoRemoved = new EventImpl();
this.observer = new MutationObserver(this.handleMutations);
this.intersectionObserver = new IntersectionObserver(
this.handleIntersections,
{ threshold: 0.1 },
);
// Initialize variables for periodic scanning
this.scanHandle = null;
this.scanInterval = 5000; // Scan every 5 seconds (adjust as needed)
this.boundScanForMissedVideos = this.scanForMissedVideos.bind(this);
}
handleMutations = (mutationsList) => {
window.requestIdleCallback(
() => {
for (let i = 0; i < mutationsList.length; i++) {
const mutation = mutationsList[i];
if (mutation.type !== "childList") continue;
const addedVideos = filterVideoNodes(mutation.addedNodes);
for (let j = 0; j < addedVideos.length; j++) {
this.checkAndHandleVideo(addedVideos[j]);
}
const removedVideos = filterVideoNodes(mutation.removedNodes);
for (let k = 0; k < removedVideos.length; k++) {
this.handleVideoRemoved(removedVideos[k]);
}
}
},
{ timeout: 1000 },
);
};
handleIntersections = (entries) => {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if (entry.isIntersecting) {
this.handleIntersectingVideo(entry.target);
}
}
};
enable() {
this.observer.observe(document, { childList: true, subtree: true });
const videos = this.getAllVideoEls();
for (let i = 0; i < videos.length; i++) {
this.checkAndHandleVideo(videos[i]);
}
// Start periodic scanning for missed videos
this.scheduleNextScan();
}
disable() {
this.observer.disconnect();
this.intersectionObserver.disconnect();
// Cancel any scheduled scans
if (this.scanHandle) {
cancelIdleCallback(this.scanHandle);
this.scanHandle = null;
}
}
getAllVideoEls() {
const videos = document.querySelectorAll("video");
if (videos.length) return Array.from(videos);
// Use it only if we don't find videos
// It takes a long time to complete
const videoElements = new Set();
const traverseShadowRoot = (root) => {
if (!root) return;
const shadowVideos = root.querySelectorAll("video");
for (let i = 0; i < shadowVideos.length; i++) {
videoElements.add(shadowVideos[i]);
}
const shadowElements = root.querySelectorAll("*");
for (let i = 0; i < shadowElements.length; i++) {
if (shadowElements[i].shadowRoot)
traverseShadowRoot(shadowElements[i].shadowRoot);
}
};
const allElements = document.querySelectorAll("*");
for (let i = 0; i < allElements.length; i++) {
if (allElements[i].shadowRoot)
traverseShadowRoot(allElements[i].shadowRoot);
}
return Array.from(videoElements);
}
checkAndHandleVideo = (video) => {
if (this.videoCache.has(video)) return;
this.videoCache.add(video);
this.intersectionObserver.observe(video);
};
handleIntersectingVideo = (video) => {
this.intersectionObserver.unobserve(video);
if (isAdVideo(video) || isMutedVideo(video)) {
debug.log("The promotional/muted video was ignored", video);
return;
}
waitForVideoReady(video, this.handleVideoAdded);
};
handleVideoAdded = (video) => {
this.onVideoAdded.dispatch(video);
};
handleVideoRemoved = (video) => {
if (!document.contains(video)) {
this.videoCache.delete(video);
this.onVideoRemoved.dispatch(video);
}
};
// New method to scan for missed videos
scanForMissedVideos() {
const allVideos = this.getAllVideoEls();
let newVideosFound = false;
for (let i = 0; i < allVideos.length; i++) {
const video = allVideos[i];
if (!this.videoCache.has(video)) {
this.checkAndHandleVideo(video);
newVideosFound = true;
}
}
if (newVideosFound) {
debug.log("Scanned for missed videos and added new ones.");
}
// Schedule the next scan
this.scheduleNextScan();
}
// Helper method to schedule the next scan using requestIdleCallback
scheduleNextScan() {
if (this.scanHandle) return; // Prevent multiple schedules
this.scanHandle = requestIdleCallback(() => {
this.scanForMissedVideos();
this.scanHandle = null;
}, { timeout: this.scanInterval });
}
}
Periodic Scanning for Missed Videos:
scanForMissedVideos Method: This new method retrieves all video elements using getAllVideoEls(). It then iterates through each video and checks if it's already present in the videoCache. If a video is not cached, it calls checkAndHandleVideo to process it.Scheduling the Scan:
scheduleNextScan Method: This helper method schedules the scanForMissedVideos to run during the browser's idle periods using requestIdleCallback. It prevents multiple scans from being scheduled simultaneously by checking if a scan is already pending (this.scanHandle).scanInterval is set to 5000 milliseconds (5 seconds) as a fallback timeout to ensure that the scan occurs even if the browser remains busy. You can adjust this interval based on your application's performance requirements.Integrating the Scan into the Observer Lifecycle:
enable Method: After initializing the observer and processing existing videos, enable now also starts the periodic scanning by calling scheduleNextScan.disable Method: When the observer is disabled, it disconnects both observers and cancels any pending scans to clean up resources properly.Handling Shadow DOM Elements:
getAllVideoEls method already traverses shadow DOMs to find video elements. The new scanning method leverages this to ensure comprehensive coverage.Performance Considerations:
requestIdleCallback, the scanning is scheduled to occur only when the browser is idle, minimizing the impact on performance.videoCache ensures that each video is processed only once, preventing redundant operations.MutationObserver are eventually processed.requestIdleCallback allows the scans to occur without disrupting the main thread or user interactions.scanInterval. A shorter interval ensures quicker detection of missed videos but may have a slight performance impact.By incorporating this periodic scanning mechanism, your VideoObserver becomes more robust, ensuring that all video elements are detected and handled appropriately, even in complex and dynamic DOM structures.
Not yet included in a published release.