diff --git a/src/components/SearchBar/SearchBar.vue b/src/components/SearchBar/SearchBar.vue index c0387361..5b11eebc 100644 --- a/src/components/SearchBar/SearchBar.vue +++ b/src/components/SearchBar/SearchBar.vue @@ -9,6 +9,7 @@ import { removeSearchHistory, } from './searchHistoryProvider' import API from '~/background/msg.define' +import { findLeafActiveElement } from '~/utils/element' defineProps<{ darkenOnFocus?: boolean @@ -32,16 +33,20 @@ watch(isFocus, async (focus) => { }) onKeyStroke('/', (e: KeyboardEvent) => { - if (e.target) { - if ((e.target as HTMLElement).tagName !== 'INPUT' - && (e.target as HTMLElement).tagName !== 'TEXTAREA' - && !(e.target as HTMLElement).className.includes('textarea') - && !(e.target as HTMLElement).className.includes('input') - ) { - e.preventDefault() - keywordRef.value?.focus() - } + // Reference: https://github.com/polywock/globalSpeed/blob/3705ac836402b324550caf92aa65075b2f2347c6/src/contentScript/ConfigSync.ts#L94 + const target = e.target as HTMLElement + const ignoreTagNames = ['INPUT', 'TEXTAREA'] + if (target && (ignoreTagNames.includes(target.tagName) || target.isContentEditable)) + return + + const activeElement = findLeafActiveElement(document) as HTMLElement | undefined + if (activeElement && target !== activeElement) { + if (ignoreTagNames.includes(activeElement.tagName) || activeElement.isContentEditable) + return } + + e.preventDefault() + keywordRef.value?.focus() }) onKeyStroke('Escape', (e: KeyboardEvent) => { e.preventDefault() diff --git a/src/utils/element.ts b/src/utils/element.ts new file mode 100644 index 00000000..c6a9aa92 --- /dev/null +++ b/src/utils/element.ts @@ -0,0 +1,16 @@ +export function getShadowRoot(v: Element) { + if (v.shadowRoot) + return v.shadowRoot +} + +export function findLeafActiveElement(doc: DocumentOrShadowRoot): Element | undefined { + const active = doc?.activeElement + if (!active) + return + + const shadowRoot = getShadowRoot(active) + if (shadowRoot && shadowRoot.activeElement) + return findLeafActiveElement(shadowRoot) + + return active +}