diff --git a/index.js b/index.js index 8d80eef..21c1ba9 100644 --- a/index.js +++ b/index.js @@ -62,6 +62,11 @@ function findNearestDialog(el) { * @param {Element} el to blur */ function safeBlur(el) { + // Find the actual focused element when the active element is inside a shadow root + while(el && el.shadowRoot && el.shadowRoot.activeElement) { + el = el.shadowRoot.activeElement; + } + if (el && el.blur && el !== document.body) { el.blur(); } @@ -108,12 +113,12 @@ function findFocusableElementInShadowDom(hostElement) { target = hostElement.querySelector(query.join(', ')); if (!target) { - // If we haven't found a focusable target, see if the host element contains any custom elements. - // While any element can technically have a shadowRoot, custom elements are likely to. + // If we haven't found a focusable target, see if the host element contains an element + // which has a shadowRoot. // Recursively search for the first focusable item in shadow roots. var elems = hostElement.querySelectorAll('*'); for (var i = 0; i < elems.length; i++) { - if (elems[i].tagName && elems[i].tagName.indexOf('-') > 0 && elems[i].shadowRoot) { + if (elems[i].tagName && elems[i].shadowRoot) { target = findFocusableElementInShadowDom(elems[i].shadowRoot); if (target) { break;