WebView2 - Update innerHTML using HtmlTextWriter

1.5k views Asked by At

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

2

There are 2 answers

0
Zimo On BEST ANSWER

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.

1
Poul Bak On

Ok, if you're happy with ignoring the new lines, then your comments work. However, if you prefer to have the newlines in your html, this is also possible.

What happens here is kind of 'Lost in translation'. You build a string in C#, then transfer it to javascript. Javascript doesn't like newlines in the middle of a literal string. That's why it fails.

The solution is quite simple, simply replace the literal newline characters (with one escape) with double escaped characters. Add this line just above your call to ExecuteScriptAsync:

value= value.Replace("\t", "\\t").Replace("\r", "\\r").Replace("\n", "\\n");

Now javascript accepts the newlines and you will get newlines in your html.