can't access property "contains", e.shadowRoot is null [code]
- User
can't access property "contains", e.shadowRoot is null
js - Assistant
can't access property "contains", e.shadowRoot is null
import "requestidlecallback-polyfill";
import { EventImpl } from "./EventImpl.js";
import debug from "./debug.ts";
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.patchAttachShadow();
}
patchAttachShadow() {
const originalAttachShadow = Element.prototype.attachShadow;
const self = this;
Element.prototype.attachShadow = function (...args) {
const shadowRoot = originalAttachShadow.apply(this, args);
self.searchInRoot(shadowRoot);
self.observeShadowRoot(shadowRoot);
return shadowRoot;
};
}
observeShadowRoot(shadowRoot) {
const shadowObserver = new MutationObserver(this.handleMutations);
shadowObserver.observe(shadowRoot, { childList: true, subtree: true });
}
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 }
);
};
/**
* Универсальная функция поиска видео внутри переданного корня (document или shadowRoot).
* @param {Document | ShadowRoot} root
*/
searchInRoot(root) {
const findVideosInRoot = (currentRoot) => {
const videos = new Set();
const searchNode = (node) => {
if (node instanceof HTMLVideoElement) {
videos.add(node);
}
if (node instanceof Element) {
const directVideos = node.querySelectorAll("video");
for (let i = 0; i < directVideos.length; i++) {
videos.add(directVideos[i]);
}
if (node.shadowRoot) {
const shadowVideos = node.shadowRoot.querySelectorAll("video");
for (let i = 0; i < shadowVideos.length; i++) {
videos.add(shadowVideos[i]);
}
searchNode(node.shadowRoot);
}
const children = node.children;
if (children) {
for (let i = 0; i < children.length; i++) {
searchNode(children[i]);
}
}
}
};
searchNode(currentRoot);
return Array.from(videos);
};
const foundVideos = findVideosInRoot(root);
for (let i = 0; i < foundVideos.length; i++) {
this.checkAndHandleVideo(foundVideos[i]);
}
}
enable() {
this.observer.observe(document, { childList: true, subtree: true });
const regularVideos = document.querySelectorAll("video");
for (let i = 0; i < regularVideos.length; i++) {
this.checkAndHandleVideo(regularVideos[i]);
}
this.searchInRoot(document);
const existingShadowHosts = this.getAllShadowHosts(document);
for (let i = 0; i < existingShadowHosts.length; i++) {
const host = existingShadowHosts[i];
if (host.shadowRoot) {
this.searchInRoot(host.shadowRoot);
this.observeShadowRoot(host.shadowRoot);
}
}
}
getAllShadowHosts(root) {
const hosts = new Set();
const traverse = (node) => {
if (node.shadowRoot) {
hosts.add(node);
const shadowElements = node.shadowRoot.querySelectorAll("*");
for (let i = 0; i < shadowElements.length; i++) {
traverse(shadowElements[i]);
}
}
const children = node.children;
if (children) {
for (let i = 0; i < children.length; i++) {
traverse(children[i]);
}
}
};
traverse(root);
return hosts;
}
disable() {
this.observer.disconnect();
}
checkAndHandleVideo = (video) => {
if (this.videoCache.has(video)) return;
this.videoCache.add(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);
}
};
}
The error message you're encountering:
"can't access property 'contains', e.shadowRoot is null"
indicates that somewhere in your code, there's an attempt to access the contains property on a shadowRoot that is null. This typically happens when the code assumes that a shadowRoot exists without properly verifying its presence.
Let's analyze your code to identify potential areas where this issue might arise and provide solutions to resolve it.
Accessing shadowRoot Without Proper Checks:
shadowRoot in several places, there might be asynchronous operations where the shadowRoot becomes null between the check and the access.Race Conditions:
shadowRoot is removed or not yet attached when the code tries to access it.External Modules:
EventImpl, debug, etc.) if they access shadowRoot without proper checks.Event Listener Context:
e) that do not have a shadowRoot, attempting to access e.shadowRoot.contains will result in the mentioned error.Ensure that every access to shadowRoot is preceded by a proper null check. This includes both direct accesses and any chained property accesses.
Example Modification in filterVideoNodes:
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) { // Check if shadowRoot exists
const shadowVideos = node.shadowRoot.querySelectorAll("video");
for (let k = 0; k < shadowVideos.length; k++) {
result.push(shadowVideos[k]);
}
}
}
return result;
};
Make sure that all similar cases in your code follow this pattern.
Modern JavaScript allows the use of optional chaining (?.) to safely access properties. This can prevent runtime errors when trying to access properties of null or undefined objects.
Example:
if (node.shadowRoot?.contains(someElement)) {
// Safe to use contains
}
Apply optional chaining wherever appropriate in your code, especially in areas dealing with shadowRoot.
When handling mutations, ensure that nodes and their shadowRoot are still valid and exist before performing operations on them.
Modify handleMutations Method:
handleMutations = (mutationsList) => {
window.requestIdleCallback(
() => {
for (let i = 0; i < mutationsList.length; i++) {
const mutation = mutationsList[i];
if (mutation.type !== "childList") continue;
// Process added nodes
const addedVideos = filterVideoNodes(mutation.addedNodes);
for (let j = 0; j < addedVideos.length; j++) {
this.checkAndHandleVideo(addedVideos[j]);
}
// Process removed nodes
const removedVideos = filterVideoNodes(mutation.removedNodes);
for (let k = 0; k < removedVideos.length; k++) {
this.handleVideoRemoved(removedVideos[k]);
}
}
},
{ timeout: 1000 }
);
};
Ensure that within checkAndHandleVideo and handleVideoRemoved, you verify the existence of shadowRoot before performing any operations.
To pinpoint the exact location of the error, add logging statements before accessing shadowRoot. This will help you identify which part of the code is attempting to access contains on a null shadowRoot.
Example:
const checkAndHandleVideo = (video) => {
if (this.videoCache.has(video)) return;
this.videoCache.add(video);
if (isAdVideo(video) || isMutedVideo(video)) {
debug.log("The promotional/muted video was ignored", video);
return;
}
waitForVideoReady(video, (video) => {
if (video.shadowRoot) { // Log presence of shadowRoot
debug.log("Video is ready and has shadowRoot", video);
} else {
debug.log("Video is ready but shadowRoot is null", video);
}
this.handleVideoAdded(video);
});
};
Examine the EventImpl and debug modules to ensure they do not access shadowRoot without proper checks. Ensure that these modules are robust against null values.
If the page dynamically creates and removes shadowRoots, ensure that your observer correctly handles these changes without assuming permanence.
Here's how you can modify parts of your code to use optional chaining, enhancing safety:
// Example in handleMutations
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 }
);
};
// Example of using optional chaining when accessing shadowRoot
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;
};
In this example, while isAdVideo doesn't directly interact with shadowRoot, any modifications or extensions that involve shadowRoot should follow the same pattern of safe access.
The error you're experiencing is likely due to attempting to access the contains property on a null shadowRoot. By implementing thorough null checks, using optional chaining, enhancing your mutation handling, and adding strategic logging, you can prevent this error from occurring and make your code more robust against dynamic DOM changes.
If after these changes you still encounter issues, consider the following:
shadowRoot is accessed, especially in the imported modules.shadowRoot consistently.Feel free to share more details if the problem persists, and I can assist further!
Not yet included in a published release.