How to use WebView2 to grab href from DOM elements

john zyd 421 Reputation points
2021-04-04T19:38:03.24+00:00

I want to know if I can use WebView2 to browse some web page, and find the links from DOM elements.
For example, I can use Edge browser to visit this web page:
https://github.com/search?q=webview2
Then from the search results returned, I can see a lot of web links.
At least some of them can be retrieved by JavaScript from Developer Tools, like this:
var links = document.getElementsByClassName('v-align-middle');

I want to know if I can run such simple JavaScript from the web page:
https://github.com/search?q=webview2
to get all the web URLs (href) from the DOM elements.
I searched around, I can’t find any helpful code example. All other codes didn’t solve my problem.
Please advise,

Developer technologies | C#
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Castorix31 90,686 Reputation points
    2021-04-05T00:03:26.72+00:00

    You can use CoreWebView2.ExecuteScriptAsync

    For example, to get the body :

    string sHtml = await webView21.CoreWebView2.ExecuteScriptAsync("document.documentElement.outerHTML");  
    string sHtmlDecoded = System.Text.RegularExpressions.Regex.Unescape(sHtml);  
    

    then you can parse sHtmlDecoded

    1 person found this answer helpful.

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.