2016-04-14 51 views
2

UWP WebView有点怪异与焦点。UWP WebView焦点

我有一个完全覆盖WebView的单页TestApp。

当App获得焦点时,WebView控件获取焦点(并接收GotFocus事件),但DOM document.hasFocus的状态保持为false。

当用户点击html时,document.hasFocus变为true,webView接收到LostFocus事件。

想要/预期的行为将是,如果应用程序/页面被激活,WebView的内容得到焦点。

有什么建议吗?

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> 

回答

0

下面的方法应该解决您的问题。在启动时执行SetRestoreFocus并提供对您的webview的参考作为参数。

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[] {}); 
    } 

重要的是,你专注于你的WebView后,你需要在你的JavaScript运行“document.focus()”。这会自动重新调整在您的应用程序被暂停或不再活动之前重点关注的html元素。