【问题标题】:UWP WebView focusUWP WebView 焦点
【发布时间】:2016-08-05 15:58:39
【问题描述】:

UWP WebView 的焦点有点奇怪。

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

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

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

想要/预期的行为是,如果 App/Page 被激活,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>

【问题讨论】:

    标签: webview win-universal-app


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多