Skip to content

Commit 662bcad

Browse files
committed
fix: crash on invalid cross origin iframe
1 parent 2f43468 commit 662bcad

File tree

3 files changed

+18
-9
lines changed

3 files changed

+18
-9
lines changed

src/getWindowEvent.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
export function getWindowEvent(ownerWindow?: Window | null) {
2+
const win = ownerWindow || window;
3+
4+
// Store the current event to avoid triggering handlers immediately
5+
// For things rendered in an iframe, the event might originate on the parent window
6+
// so we should fall back to that global event if the local one doesn't exist
7+
// https://github.com/facebook/react/issues/20074
8+
try {
9+
return win.event ?? win.parent?.event;
10+
} catch (err) {
11+
// catch iframe security errors and fallback to nothing
12+
return undefined;
13+
}
14+
}

src/useClickOutside.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useRef } from 'react';
55

66
import useEventCallback from '@restart/hooks/useEventCallback';
77
import warning from 'warning';
8+
import { getWindowEvent } from './getWindowEvent.js';
89

910
const noop = () => {};
1011

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

102103
const doc = ownerDocument(getRefTarget(ref)!);
103-
const ownerWindow = doc.defaultView || window;
104104

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

111107
let removeInitialTriggerListener: (() => void) | null = null;
112108
if (InitialTriggerEvents[clickTrigger]) {

src/useRootClose.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import useClickOutside, {
88
getRefTarget,
99
} from './useClickOutside.js';
1010
import { isEscKey } from './utils.js';
11+
import { getWindowEvent } from './getWindowEvent.js';
1112

1213
const noop = () => {};
1314

@@ -47,9 +48,7 @@ function useRootClose(
4748

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

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

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

0 commit comments

Comments
 (0)