Home > Software engineering >  Insert text into Webview2
Insert text into Webview2

Time:09-04

I have a very weird error

I am successfully inserting a text into a website, using this code

public SpellCheckWindow(string txt)
{
    InitializeComponent();
    ConfigureSite();
    Txt = txt;
}

private async void ConfigureSite()
{
    await web.EnsureCoreWebView2Async();
    web.Source = new Uri("https://quillbot.com/grammar-check");
    web.NavigationCompleted  = Web_NavigationCompleted;
}

private async void Web_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
{
    var msg = "Hello from a newly loaded .NET window.";
    var elem = await web.ExecuteScriptAsync($"document.getElementById('grammarbot').innerText = '{msg}';");
}

The strange part is that if I change the message for my text, it doesn't show anything

This is a screenshot with the message:

enter image description here

And if I change the Msg for my Txt

enter image description here

Nothing shows up, and I do not know why.

Also by any chance, somebody knows how to get rea of the placeholder "Enter your text"

I thought it was a limitation of the site, but I went to the site and I pasted my Txt

Btw, the Txt is not empty

"I believe we have some power over who we love. It isn't just something that happens to a person. And yes, you can stand there and tell me that the poets would disagree, but I am not a poet. I am just a woman and as a woman I have no way to make money. Not enough to earn a living and support my family. Even if I had my own money, which I don't, it would belong to my husband the minute we were married. If we have children, they belong to him, not me. They are his property. So don't sit there and tell me that marriage isn't an economic proposition, because it is. It may not be for you. But it most certainly is for me. That will be Fred now. How do I look? Do I look alright?"

CodePudding user response:

You need to escape your text before insertings into js. In the js you are using ' symbol as the strings begin/end. And there are the same symbols exists into your msg. So, when you insertings unescaped msg, the js engine will think that the js string is ended somewhere in the middle of the text, then see the remainint text and throw the error. You can use HttpUtility.JavaScriptStringEncode to escape the text

  • Related