@@ -61,31 +61,34 @@ protected override async Task OnAfterRenderAsync(bool firstRender)
6161
6262 private void ShowDialog ( IDialogReference dialogReference , Type ? dialogComponent , DialogParameters parameters , object content )
6363 {
64- if ( _module is null )
65- {
66- throw new InvalidOperationException ( "JS module is not loaded." ) ;
67- }
68-
6964 InvokeAsync ( async ( ) =>
7065 {
71- var previouslyFocusedElement = await _module . InvokeAsync < IJSObjectReference > ( "getActiveElement" ) ;
66+ var previouslyFocusedElement = await GetPreviouslyFocusedElementAsync ( ) ;
67+
7268 DialogInstance dialog = new ( dialogComponent , parameters , content , previouslyFocusedElement ) ;
7369 dialogReference . Instance = dialog ;
7470
7571 _internalDialogContext . References . Add ( dialogReference ) ;
7672 } ) ;
7773 }
7874
79- private async Task < IDialogReference > ShowDialogAsync ( IDialogReference dialogReference , Type ? dialogComponent , DialogParameters parameters , object content )
75+ private async Task < IJSObjectReference ? > GetPreviouslyFocusedElementAsync ( )
8076 {
81- if ( _module is null )
77+ // If the module hasn't been loaded then the page hasn't rendered yet, so there is no previously focused element.
78+ IJSObjectReference ? previouslyFocusedElement = null ;
79+ if ( _module is not null )
8280 {
83- throw new InvalidOperationException ( "JS module is not loaded. ") ;
81+ previouslyFocusedElement = await _module . InvokeAsync < IJSObjectReference > ( "getActiveElement ") ;
8482 }
8583
84+ return previouslyFocusedElement ;
85+ }
86+
87+ private async Task < IDialogReference > ShowDialogAsync ( IDialogReference dialogReference , Type ? dialogComponent , DialogParameters parameters , object content )
88+ {
8689 return await Task . Run ( async ( ) =>
8790 {
88- var previouslyFocusedElement = await _module . InvokeAsync < IJSObjectReference > ( "getActiveElement" ) ;
91+ var previouslyFocusedElement = await GetPreviouslyFocusedElementAsync ( ) ;
8992
9093 DialogInstance dialog = new ( dialogComponent , parameters , content , previouslyFocusedElement ) ;
9194 dialogReference . Instance = dialog ;
@@ -166,12 +169,12 @@ internal void DismissInstance(string id, DialogResult result)
166169
167170 internal async Task ReturnFocusAsync ( IJSObjectReference element )
168171 {
169- if ( _module is null )
172+ // Module should always be loaded here, but check just in case.
173+ if ( _module is not null )
170174 {
171- throw new InvalidOperationException ( "JS module is not loaded." ) ;
175+ await _module . InvokeVoidAsync ( "focusElement" , element ) ;
172176 }
173177
174- await _module . InvokeVoidAsync ( "focusElement" , element ) ;
175178 await element . DisposeAsync ( ) ;
176179 }
177180
0 commit comments