如何将webkitRequestFullscreen()注入UWP WebView

时间:2016-10-23 00:37:56

标签: javascript c# webview uwp

我在UWP应用程序中有一个WebView控件,用于加载Steam广播页面URL。它运作良好,我还有一个全屏按钮,可以将整个窗口切换到全屏。

但Steam广播有自己的全屏切换按钮,我想以编程方式点击,这样当我按下全屏按钮时,窗口和广播都会切换到全屏。

我尝试通过JS注入来实现这一点,但似乎webkitRequestFullscreen()函数仅在事件处理程序中调用时才响应。如何将事件处理程序注入WebView并调用它?

WebView

这是XAML:

<Grid Background="{StaticResource AppBackgroundColor}">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>

    <WebView Grid.Row="0" x:Name="Browser" />

    <CommandBar x:Name="WatchCommandBar" Grid.Row="1" FlowDirection="LeftToRight">
        <AppBarButton Icon="FullScreen" Label="Full Screen" Tapped="AppBarFullScreenButton_Tapped" />
    </CommandBar>
</Grid>

这是C#:

private void AppBarFullScreenButton_Tapped(object sender, RoutedEventArgs e)
{
    var view = ApplicationView.GetForCurrentView();

    if (view.IsFullScreenMode)
    {
        view.ExitFullScreenMode();
        WatchCommandBar.Visibility = Visibility.Visible;
    }
    else
    {
        view.TryEnterFullScreenMode();
        WatchCommandBar.Visibility = Visibility.Collapsed;
    }
}

我在切换到全屏时尝试调用这些函数,但它们都不起作用:

await Browser.InvokeScriptAsync("eval", new [] { "BroadcastWatch.m_playerUI.ToggleFullscreen();" });
await Browser.InvokeScriptAsync("eval", new [] { "document.getElementById('videoplayer').webkitRequestFullscreen();" });

1 个答案:

答案 0 :(得分:0)

显然,无法注入全屏请求。而且我无法欺骗理论上会提出请求的鼠标点击事件。

作为一种解决方法,我最终隐藏并设置了在WebView加载完成后注入此脚本时我不想看到的元素:

private async void Browser_HideElements(object sender, WebViewDOMContentLoadedEventArgs args)
{
    try
    {
        var elementsToHide = "#global_header, #footer_spacer, #footer_responsive_optin_spacer, #footer, #ChatWindow, .BroadcastInfoWrapper, .fullscreen_button";

        // Hide HTML elements and change styles so it looks like the broadcast is in full-screen
        // We can't call the broadcast's own toggle full-screen function
        var lines = new[]
        {
            "document.body.style.overflow = 'hidden';",
            "document.getElementById('video_wrapper').className += ' fullscreen';",
            "document.getElementById('video_content').style.padding = 0;",
            "document.getElementById('video_content').style.margin = 0;",
            "document.getElementsByClassName('pagecontent')[0].style.padding = 0;",
            "var list = document.querySelectorAll('" + elementsToHide + "');",
            "for (var i = 0; i < list.length; i++) { var e = list[i]; e.style.display = 'none'; }"
        };
        await Browser.InvokeScriptAsync("eval", new[] { string.Join(" ", lines) });
    }
    catch
    {
        // Ignore script exceptions
    }
}

所以看起来广播是全屏运行的,当按下我自己的按钮时,标题栏会消失,并进入正常的全屏。

WebView