Need help to run JavaScript in WebVeiw2

john zyd 421 Reputation points
2020-12-30T08:30:57.023+00:00

Hello:

Quite some time ago, I used WebView in XML project, I can use WebView to inject JavaScript, run it and get string result in C#.

But now, with the new WebVew2 coming, I want to find a good example to inject a custom JavaScript and return the string result, but I can’t find a good example.

For example:

I created one Windows Forms .NET Framework App project (target .net framework 4.8), then downloaded Edge Canary for Windows 10, install WebView2 nuget package:

Install-Package Microsoft.Web.WebView2 -Version 1.0.664.37; then from Toolbox. Drag and drop the WebView2 control, and changed its source to https://www.bing.com/

Now, in Edge Canary, when I browsed to https://www.bing.com/; I can open developer tools, and under “console” tab, run a small JavaScript:

var divs = document.getElementsByTagName('div');

var div_length = divs.length;

console.log(div_length);

I can run this, and saw the output: 189

My question is: how I can run such small JavaScript in one WebView2 program to see the result. I wrote some code to do the similar thing on many different web sites, I can only see the result is null.

Please someone show me some code on how to do this.

By the way, my IDE is: Visual Studio 2019 Version 16.8.3 on Windows 10 (Version 20H2 OS build 19042.685)

Developer technologies Windows Forms
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Tianyu Sun-MSFT 34,436 Reputation points Microsoft External Staff
    2020-12-31T08:05:07.3+00:00

    Hi @john zyd ,

    Thank you for taking time to post this issue in Microsoft Q&A forum.

    Perhaps, you can try to use OpenDevToolsWindow() and ExecuteScriptAsync() methods to make it work(CoreWebView2 Class - Methods).

    The code snippets may be like this:

    52419-webview.png

    The result:

    52465-webview.gif

    • Update1:

    This issue should be caused by programming of JS, and please try these codes

    54002-webview1.png

    and note that I set two controls, one WebView2 control and one TextBox control, and named them webView21 and textBox1. The textBox1 is used to view the result(value).

    Best Regards,
    Tianyu

    • If the answer is helpful, please click "Accept Answer" and upvote it.
      Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.