Reputation: 21
UWP WebView acts bit weird with focuses.
I have a single-page TestApp that is fully covered with WebView.
When App gets a focus, WebView control gets focus (and receives GotFocus event), but the the state of DOM document.hasFocus remains false.
When user clicks on the html, document.hasFocus becomes true and webView receives LostFocus event.
The wanted/expected behavior would be that if App/Page is activated, the content of the WebView gets the focus.
Any suggestions?
XAML:
<Page
x:Class="TestApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<WebView x:Name="webView" NavigationStarting="webView_NavigationStarting" GotFocus="webView_GotFocus" LostFocus="webView_LostFocus"/>
</Grid>
</Page>
Upvotes: 2
Views: 938
Reputation: 301
The following methods should fix your issue. Execute SetRestoreFocus at startup and provide a reference to your webview as parameter.
private static void SetRestoreFocus(WebView webView)
{
Window.Current.Activated += async (object sender, WindowActivatedEventArgs e) =>
{
if (e.WindowActivationState != CoreWindowActivationState.Deactivated)
{
await RestoreFocus(webView);
}
};
Application.Current.Resuming += async (object sender, object e) =>
{
await RestoreFocus(webView);
};
}
private static async Task RestoreFocus(WebView webView)
{
webView.Focus(FocusState.Programmatic);
await webView.InvokeScriptAsync("document.focus", new string[] {});
}
The important thing is that after you focus your webview, you need to run "document.focus()" in your javascript. This will automatically refocus the html element which was in focus before your app was suspended or no more active.
Upvotes: 1