UWP WebView 等待导航 [英] UWP WebView await navigate

查看:32
本文介绍了UWP WebView 等待导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在由 JavaScript 呈现的网站上获取一些内容.所以我正在运行一个带有 Visibility=CollapsedWebView.我想等待 unitl NavigationCompleted 并运行一些 JavaScript 然后返回值.

I'm trying to get some content on a website which is rendered by JavaScript. So I'm running a WebView with Visibility=Collapsed. I want to wait unitl NavigationCompleted and run some JavaScript then return the value.

代码如下:

private async void Foo()
{
    // Want to get value here
    var content = await GetContent();
}

private async Task<string> GetContent()
{
    string content;
    async void handler(WebView sender, WebViewNavigationCompletedEventArgs args)
    {
        content = await webView.InvokeScriptAsync("eval", new string[] { script });
        webView.NavigationCompleted -= handler;
    }
    webView.NavigationCompleted += handler;
    webView.Navigate(uri);
    return content;
}

由于 GetContent() 中没有 await,所以函数总是在 NavigationCompleted 触发之前返回.

Since there is no await in GetContent(), the function always returns before NavigationCompleted fired.

推荐答案

您可以使用 SemaphoreSlim 异步等待 NavigationCompleted 被引发和处理:

You could use a SemaphoreSlim to asynchronously wait for the NavigationCompleted to get raised and handled:

private async Task<string> GetContent()
{
    string content;
    using (SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0, 1))
    {
        async void handler(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            content = await webView.InvokeScriptAsync("eval", new string[] { script });
            webView.NavigationCompleted -= handler;
            semaphoreSlim.Release();
        }
        webView.NavigationCompleted += handler;
        webView.Navigate(uri);
        await semaphoreSlim.WaitAsync().ConfigureAwait(false);
    }
    return content;
}

这篇关于UWP WebView 等待导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆