Webview UWP网络视图焦点

Webview UWP网络视图焦点,webview,win-universal-app,Webview,Win Universal App,UWP WebView的焦点行为有点怪异 我有一个完全由WebView覆盖的单页TestApp 当应用程序获得焦点时,WebView控件获得焦点(并接收GotFocus事件),但DOM document.hasFocus的状态仍然为false 当用户单击html时,document.hasFocus变为true,webView接收LostFocus事件 想要/期望的行为是,如果应用程序/页面被激活,WebView的内容将获得焦点 有什么建议吗 XAML: 以下方法可以解决您的问题。在启动时执行S

UWP WebView的焦点行为有点怪异

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

当应用程序获得焦点时,WebView控件获得焦点(并接收GotFocus事件),但DOM document.hasFocus的状态仍然为false

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

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

有什么建议吗

XAML:


以下方法可以解决您的问题。在启动时执行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元素

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