Skip to content

Commit

Permalink
Merge pull request #4 from knuton/use-modal-selector-safely
Browse files Browse the repository at this point in the history
Wrap use of ':modal' selector in try-catch block
  • Loading branch information
krksgbr authored Feb 15, 2024
2 parents 090a5a0 + c8e23e4 commit 0f9ad4b
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,17 +286,24 @@ function applyFocus(direction, origin, target) {
* @returns {Element}
*/
function getBlockingElement() {
// Try top-layer pseudo class (2022+ browsers)
let trapElements = document.querySelectorAll(":modal")
/** @type {Element[]} */
let trapElements = []
try {
// Try top-layer pseudo class (2022+ browsers)
trapElements = Array.from(document.querySelectorAll(":modal"))
} catch (e) {
logging.debug("Browser does not support ':modal' selector, ignoring.")
}
// If none, use fallback selector
if (trapElements.length === 0) {
trapElements = document.querySelectorAll("dialog[open], [data-focus-trap]")
trapElements = Array.from(
document.querySelectorAll("dialog[open], [data-focus-trap]")
)
}

// If no explicit trap elements were found, body is the top element
return (
getMinimumBy(Array.from(trapElements), (elem) => -getTrapIndex(elem)) ||
document.body
getMinimumBy(trapElements, (elem) => -getTrapIndex(elem)) || document.body
)
}

Expand Down

0 comments on commit 0f9ad4b

Please sign in to comment.