Home > Blockchain >  WebView2.ExecuteStriptAsync task blocked forewer
WebView2.ExecuteStriptAsync task blocked forewer

Time:11-25

When I try to read the content of one web page loaded into the webview2 control, task ExecuteScriptAsync blocks forever. After this the application does not respond, but the site is still operational. The site is posted on an corprate intranet, so I can't provide the URL here. It is Ivanti Service Desk.

private void bnNewReguest_Click(object sender, EventArgs e)
{
    var t = GetTextAsync();
    string sHtml = t.Result;
    if (!sHtml.Contains("shortcutItem_12345"))
    {
        MessageBox.Show("Please wait for the page to load");
        return;
    }
    webView21.ExecuteScriptAsync("document.getElementById('shortcutItem_12345').click()");
}

private async Task<string> GetTextAsync()
{

    if (webView21.CoreWebView2 == null)
    {
        MessageBox.Show("Wait a moment...");
        return "";
    }
    var script = "document.documentElement.outerHTML";
    string sHtml = await webView21.CoreWebView2.ExecuteScriptAsync(script);  // deadlock
    string sHtmlDecoded = System.Text.RegularExpressions.Regex.Unescape(sHtml);
    return sHtmlDecoded;
}

I also tried the code below, but the result is similar.

string sHtml = await webView21.CoreWebView2.ExecuteScriptAsync(script).ConfigureAwait(false);

The WebView2 version is 1.0.1418.22. How can I protect from deadlock? I found a thread about the same problem here, but none of the solutions work for me.

CodePudding user response:

I describe this deadlock on my blog. The best solution is to not block on asynchronous code.

In your case, this could look like this:

private async void bnNewReguest_Click(object sender, EventArgs e)
{
    string sHtml = await GetTextAsync();
    if (!sHtml.Contains("shortcutItem_12345"))
    {
        MessageBox.Show("Please wait for the page to load");
        return;
    }
    await webView21.ExecuteScriptAsync("document.getElementById('shortcutItem_12345').click()");
}
  • Related