1

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

Zimo
  • 312
  • 5
  • 21

2 Answers2

1

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.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
  • That's right. I used `HTMLTextWriter` to render the content and it was adding the new lines by default. That did not cause problems with `WebBrowser` until I started programming with `WebView2`. My solution was to set the `NewLine` property to `string.Empty`. – Zimo Apr 08 '21 at 12:29
1

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.

Zimo
  • 312
  • 5
  • 21