首页 > 解决方案 > 尝试从 UWP WebView 获取 html 时出现异常(HRESULT 异常:0x80020101)

问题描述

我需要从 WebView 获取 html。我在网上找到了以下代码:

public MainPage()
{
    this.InitializeComponent();
    WebView wb = new WebView();
    wb.Navigate(new Uri(@"https://www.microsoft.com/"));
    Thread.Sleep(1500);
    F(wb);
}
public async void F(WebView webView)
{
    var siteHtML = await webView.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
}

不幸的是,InvokeScriptAsync 方法返回错误,我根本不懂脚本。您还有其他方法可以从 WebView 获取 html,或者您可以修复我的代码吗?

标签: javascriptuwp

解决方案


尝试从 UWP WebView 获取 html 时出现异常(HRESULT 异常:0x80020101)

问题是 WebView 没有导航完成,对于这种情况,您可以在NavigationCompleted事件中调用 eval 函数。在测试过程中,它运行良好。

wb.Navigate(new Uri(@"https://www.microsoft.com/"));
wb.NavigationCompleted += Wb_NavigationCompleted;

.....

private async void Wb_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    var siteHtML = await wb.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
}

推荐阅读