clipper: add safe querySelector method

This commit is contained in:
Ammar Ahmed
2024-09-09 14:55:24 +05:00
committed by Ammar Ahmed
parent 2f7b8d3377
commit 2cb4a10076
2 changed files with 15 additions and 3 deletions

View File

@@ -20,6 +20,7 @@ import { constructUrl, FetchOptions } from "./fetch";
import { compare, calculate, SpecificityArray } from "specificity";
import { tokenize } from "./css-tokenizer";
import { stringify, parse, SelectorType } from "css-what";
import { safeQuerySelectorAll } from "./utils";
const SHORTHANDS = [
"animation",
@@ -186,7 +187,8 @@ function walkRules(
for (const selector of selectors) {
if (!selector || !selector.selector.trim()) continue;
const elements = document.querySelectorAll(
const elements = safeQuerySelectorAll(
document,
selector.selector
) as NodeListOf<StyleableElement>;
@@ -210,7 +212,8 @@ function walkRules(
}
}
const elements = document.querySelectorAll(
const elements = safeQuerySelectorAll(
document,
rule.selectorText
) as NodeListOf<StyleableElement>;

View File

@@ -165,6 +165,14 @@ function getRootStylesheet() {
return null;
}
function safeQuerySelectorAll(root: Node, selector: string) {
try {
return (root as HTMLElement).querySelectorAll(selector);
} catch (e) {
return new NodeList();
}
}
export {
injectCss,
escape,
@@ -179,5 +187,6 @@ export {
asArray,
escapeXhtml,
width,
height
height,
safeQuerySelectorAll
};