@@ -268,6 +268,7 @@ const Modal: React.ForwardRefExoticComponent<
268
268
} : ModalProps ,
269
269
ref : React . Ref < ModalHandle > ,
270
270
) => {
271
+ const ownerWindow = useWindow ( ) ;
271
272
const container = useWaitForDOMRef ( containerRef ) ;
272
273
const modal = useModalManager ( providedManager ) ;
273
274
@@ -279,7 +280,9 @@ const Modal: React.ForwardRefExoticComponent<
279
280
useImperativeHandle ( ref , ( ) => modal , [ modal ] ) ;
280
281
281
282
if ( canUseDOM && ! prevShow && show ) {
282
- lastFocusRef . current = activeElement ( ) as HTMLElement ;
283
+ lastFocusRef . current = activeElement (
284
+ ownerWindow ?. document ,
285
+ ) as HTMLElement | null ;
283
286
}
284
287
285
288
// TODO: I think this needs to be in an effect
@@ -312,7 +315,9 @@ const Modal: React.ForwardRefExoticComponent<
312
315
// autofocus after onShow to not trigger a focus event for previous
313
316
// modals before this one is shown.
314
317
if ( autoFocus ) {
315
- const currentActiveElement = activeElement ( document ) as HTMLElement ;
318
+ const currentActiveElement = activeElement (
319
+ modal . dialog ?. ownerDocument ?? ownerWindow ?. document ,
320
+ ) as HTMLElement | null ;
316
321
317
322
if (
318
323
modal . dialog &&
@@ -368,7 +373,7 @@ const Modal: React.ForwardRefExoticComponent<
368
373
return ;
369
374
}
370
375
371
- const currentActiveElement = activeElement ( ) ;
376
+ const currentActiveElement = activeElement ( ownerWindow ?. document ) ;
372
377
373
378
if (
374
379
modal . dialog &&
0 commit comments