webview2htmltextwriter

WebView2 - Update innerHTML using HtmlTextWriter


Is it possible to set/update the innerHTML with the ExecuteScriptAsync method in WebView2, or is there another way around it?

I created the below method to update the DOM. It works fine except for innerHTML

private async Task UpdateElementAsync(string elementID, string property, string value)
{
      try
      {
          await this.navigation.CoreWebView2.ExecuteScriptAsync("document.getElementById('" + elementID + "')." + property + " = \'" + value + "\'");
      }
      catch (Exception ex)
      { MessageBox.Show(ex.Message); }
        
 }

I call this method this way:

await UpdateElementAsync("DIV_ID", "innerHTML", content);

"content" is a string generated by a HTMLTextWriter

Update:

innerHTML does not like newlines (\r\n)

innerHTML Update Works: <button> test </button>

innerHTML Update does not work: <button> test </button>\r\n


Solution

  • I figure it out!.

    The issue was that I was rendering the content with HTMLTextWriter and that generates new lines ... The ExecuteScriptAsync method does not know how to interpret \r\n. My solution is to set the NewLine property of the HTMLTextWriter to a string.Empty.