3

In my WebView2 i load my local html with js file, all works fine, but how can i run a script from my WinForm in WebView?

Till now i was using webBrowser in VB and i was doing it like this:

WebBrowser1.Document.InvokeScript("addProducts", New String() {"{ ""desc"": ""test"", ""qta"": 1, ""prezzo"": 2}"})

And now i was trying something like:

private async void prodotto_Click(object sender, EventArgs e)
{
    await webView21.ExecuteScriptAsync("addProducts(\"{ \"desc\": \"test\", \"qta\": 1, \"prezzo\": 2})\"");
}

I've tryed it even like :

private void prodotto_Click(object sender, EventArgs e)
{
    AddProduct();
}

async void AddProduct()
{
    await webView21.CoreWebView2.ExecuteScriptAsync("addProducts(\"{ \"desc\": \"test\", \"qta\": 1, \"prezzo\": 2})\"");
}

But the script is not even reached...

Kasper Juner
  • 832
  • 3
  • 15
  • 34

1 Answers1

5

you have typo error in your string, try:

"addProducts({\"desc\":\"test\",\"qta\":1,\"prezzo\":2})"

Data needs to be encoded as JSON to embed as string , its better to use SerializeObject to convert object to JSON, somthing like :

  dynamic obj = new System.Dynamic.ExpandoObject();
  obj.desc = "test";
  obj.qta = 1;
  obj.prezzo = 2; 

  string  data = JsonConvert.SerializeObject(obj);

  webView21.ExecuteScriptAsync($"addProducts({data})");
NajiMakhoul
  • 1,623
  • 2
  • 16
  • 30
  • That's working as expected and i don't need any extention, the issue in JS part was that in old WebBrowser i was passing a string and parsing it while with that solution i don't need more JSON.parse – Kasper Juner Feb 03 '21 at 10:33