Search code examples
c#webview2

How to execute script using webview2 to expand an html element using c#


I'm not quite sure how to ask this question. So I'm attaching two images

enter image description here

enter image description here

How can I expand the Product Details tab so that the html rendered in the webview2 control looks like the second picture using code behind?


Solution

  • You can inject script into a page using CoreWebView2.ExecuteScriptAsync that will find that element and perform a click on it. However, this will be a fragile solution since if the layout of the page or names of elements on the page change your script may no longer work.

    I would recommend opening the desired page in the Edge browser, opening DevTools, Console, and trying out different script to click on the correct element. For example document.getElementById("product-section-overview").children[0].children[0].click() might work but depends on the ID of that element not changing, and the structure and order of its children.

    Once you have the script you want you can inject it into the document via

    await myWebView2.CoreWebView2.ExecuteScriptAsync("document.getElementById("product-section-overview").children[0].children[0].click()");