@@ -268,6 +268,7 @@ const Modal: React.ForwardRefExoticComponent<
268268 } : ModalProps ,
269269 ref : React . Ref < ModalHandle > ,
270270 ) => {
271+ const ownerWindow = useWindow ( ) ;
271272 const container = useWaitForDOMRef ( containerRef ) ;
272273 const modal = useModalManager ( providedManager ) ;
273274
@@ -279,7 +280,9 @@ const Modal: React.ForwardRefExoticComponent<
279280 useImperativeHandle ( ref , ( ) => modal , [ modal ] ) ;
280281
281282 if ( canUseDOM && ! prevShow && show ) {
282- lastFocusRef . current = activeElement ( ) as HTMLElement ;
283+ lastFocusRef . current = activeElement (
284+ ownerWindow ?. document ,
285+ ) as HTMLElement | null ;
283286 }
284287
285288 // TODO: I think this needs to be in an effect
@@ -312,7 +315,9 @@ const Modal: React.ForwardRefExoticComponent<
312315 // autofocus after onShow to not trigger a focus event for previous
313316 // modals before this one is shown.
314317 if ( autoFocus ) {
315- const currentActiveElement = activeElement ( document ) as HTMLElement ;
318+ const currentActiveElement = activeElement (
319+ modal . dialog ?. ownerDocument ?? ownerWindow ?. document ,
320+ ) as HTMLElement | null ;
316321
317322 if (
318323 modal . dialog &&
@@ -368,7 +373,7 @@ const Modal: React.ForwardRefExoticComponent<
368373 return ;
369374 }
370375
371- const currentActiveElement = activeElement ( ) ;
376+ const currentActiveElement = activeElement ( ownerWindow ?. document ) ;
372377
373378 if (
374379 modal . dialog &&
0 commit comments