From d0558b292d10d983ef01645c9d8fcbb9bcf9bde5 Mon Sep 17 00:00:00 2001 From: Matteo Borgato Date: Tue, 15 Jul 2025 15:20:14 -0300 Subject: [PATCH] fix: get ownerDocument before calling element.evaluate(...) refactor: extract getOwnerDocument helper function to follow DRY principle --- .../features/broker-protection/utils/utils.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/injected/src/features/broker-protection/utils/utils.js b/injected/src/features/broker-protection/utils/utils.js index 8429232ead..b30d02266d 100644 --- a/injected/src/features/broker-protection/utils/utils.js +++ b/injected/src/features/broker-protection/utils/utils.js @@ -1,3 +1,13 @@ +/** + * Gets the owner document of an element or uses document as fallback + * + * @param {Node|Element} element + * @return {Document} The owner document + */ +function getOwnerDocument(element) { + return element.ownerDocument || document; +} + /** * Get a single element. * @@ -75,7 +85,8 @@ export function getElementMatches(element, selector) { * @return {boolean} */ function matchesXPath(element, selector) { - const xpathResult = document.evaluate(selector, element, null, XPathResult.BOOLEAN_TYPE, null); + const ownerDoc = getOwnerDocument(element); + const xpathResult = ownerDoc.evaluate(selector, element, null, XPathResult.BOOLEAN_TYPE, null); return xpathResult.booleanValue; } @@ -131,7 +142,8 @@ function safeQuerySelector(element, selector) { */ function safeQuerySelectorXPath(element, selector) { try { - const match = document.evaluate(selector, element, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); + const ownerDoc = getOwnerDocument(element); + const match = ownerDoc.evaluate(selector, element, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); const single = match?.singleNodeValue; if (single) { return /** @type {HTMLElement} */ (single); @@ -150,8 +162,9 @@ function safeQuerySelectorXPath(element, selector) { */ function safeQuerySelectorAllXpath(element, selector) { try { + const ownerDoc = getOwnerDocument(element); // gets all elements matching the xpath query - const xpathResult = document.evaluate(selector, element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + const xpathResult = ownerDoc.evaluate(selector, element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); if (xpathResult) { /** @type {HTMLElement[]} */ const matchedNodes = [];