5

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...

5
  • You have typo: addProcuts should be addProducts !!! Commented Feb 3, 2021 at 9:40
  • @PoulBak i just writed it by hand, in actual code it's write correctly Commented Feb 3, 2021 at 9:42
  • May be see this: stackoverflow.com/questions/62835549/… Commented Feb 3, 2021 at 9:46
  • Another typo: You're missing @ in front of your verbatim string. Commented Feb 3, 2021 at 10:01
  • @PoulBak the extention from linked question works, but the object sent with ExecuteScriptFunctionAsync("addProducts", new { desc= "test", qta= 1, prezzo= 2 }); fails in JSON.parse Commented Feb 3, 2021 at 10:24

1 Answer 1

9

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})");
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.