Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/getWindowEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export function getWindowEvent(ownerWindow?: Window | null) {
const win = ownerWindow || window;

// Store the current event to avoid triggering handlers immediately
// For things rendered in an iframe, the event might originate on the parent window
// so we should fall back to that global event if the local one doesn't exist
// https://github.com/facebook/react/issues/20074
try {
return win.event ?? win.parent?.event;
} catch (err) {
// catch iframe security errors and fallback to nothing
return undefined;
}
}
8 changes: 2 additions & 6 deletions src/useClickOutside.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useCallback, useEffect, useRef } from 'react';

import useEventCallback from '@restart/hooks/useEventCallback';
import warning from 'warning';
import { getWindowEvent } from './getWindowEvent.js';

const noop = () => {};

Expand Down Expand Up @@ -100,13 +101,8 @@ function useClickOutside(
if (disabled || ref == null) return undefined;

const doc = ownerDocument(getRefTarget(ref)!);
const ownerWindow = doc.defaultView || window;

// Store the current event to avoid triggering handlers immediately
// For things rendered in an iframe, the event might originate on the parent window
// so we should fall back to that global event if the local one doesn't exist
// https://github.com/facebook/react/issues/20074
let currentEvent = ownerWindow.event ?? ownerWindow.parent?.event;
let currentEvent = getWindowEvent(doc.defaultView);

let removeInitialTriggerListener: (() => void) | null = null;
if (InitialTriggerEvents[clickTrigger]) {
Expand Down
5 changes: 2 additions & 3 deletions src/useRootClose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import useClickOutside, {
getRefTarget,
} from './useClickOutside.js';
import { isEscKey } from './utils.js';
import { getWindowEvent } from './getWindowEvent.js';

const noop = () => {};

Expand Down Expand Up @@ -47,9 +48,7 @@ function useRootClose(

const doc = ownerDocument(getRefTarget(ref)!);

// Store the current event to avoid triggering handlers immediately
// https://github.com/facebook/react/issues/20074
let currentEvent = (doc.defaultView || window).event;
let currentEvent = getWindowEvent(doc.defaultView);

const removeKeyupListener = listen(doc as any, 'keyup', (e) => {
// skip if this event is the same as the one running when we added the handlers
Expand Down
Loading