isEventForTarget rejects any target that isn't the ambient document/window, breaking registrations against other windows/documents #155
Summary#
HotkeyManager.register() accepts target: HTMLElement | Document | Window | null and correctly attaches the underlying addEventListener to whatever is passed. But the internal match filter, isEventForTarget in src/_event-target.ts, only recognizes the ambient document / window of the module's own scope:
export function isEventForTarget(event, target) {
if (target === document || target === window) {
return event.currentTarget === target || event.currentTarget === document.documentElement
}
if (target === window) { ... } // unreachable, already covered above
if (target instanceof HTMLElement) { ... }
return false
}
If target is a Document (or Window) other than the ambient one — for example another browser window opened via window.open(), which is a real use case for a multi-window app (a popped-out panel, a detached devtools-style window, etc.) — this function always falls through to return false, even though the listener was correctly attached to that exact target and event.currentTarget genuinely equals it when the handler fires.
The registration silently never fires. No error, no warning.
(Side note: the second if (target === window) branch is unreachable, since the first condition already covers it.)
Minimal repro#
const manager = HotkeyManager.getInstance()
const otherDoc = document.implementation.createHTMLDocument()
let fired = false
manager.register('Mod+S', () => { fired = true }, { target: otherDoc })
otherDoc.dispatchEvent(new KeyboardEvent('keydown', { key: 's', metaKey: true, bubbles: true }))
// fired === false, even though the listener was attached to otherDoc
Suggested fix#
Check event.currentTarget === target unconditionally first, and keep the Brave document.documentElement fallback only for the ambient-document/window case:
export function isEventForTarget(event, target) {
if (event.currentTarget === target) return true
if ((target === document || target === window) && event.currentTarget === document.documentElement) return true
if (target instanceof HTMLElement && event.target instanceof Node && target.contains(event.target)) return true
return false
}
The leading check is realm-safe — it's a reference comparison, not an instanceof check — since event.currentTarget during a listener invocation is always the exact node/document/window the listener was attached to.
Happy to open a PR with this fix plus tests if that's useful — verified working against v0.9.0 locally.
Sign in to join this conversation.
Closed as not relevant currently.