From 5a6e55c71fb0d4e785d3e76aa98be043a5e5a3ef Mon Sep 17 00:00:00 2001 From: jquense Date: Mon, 22 May 2023 10:48:39 -0400 Subject: [PATCH] fix(useOutsideClick): fix a case where click outside fired twice in a row in an iframe --- src/useClickOutside.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/useClickOutside.ts b/src/useClickOutside.ts index b9699ea..f9ef747 100644 --- a/src/useClickOutside.ts +++ b/src/useClickOutside.ts @@ -95,10 +95,13 @@ 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 = (doc.defaultView || window).event; + let currentEvent = ownerWindow.event ?? ownerWindow.parent?.event; let removeInitialTriggerListener: (() => void) | null = null; if (InitialTriggerEvents[clickTrigger]) {