简体   繁体   中英

How can I get the image src?

I'm using a WebView2 on Windows Forms. I want to get that image src from html and show it in a MessageBox

 <div class="col-sm-6" style="z-index:900;padding:0"> <img id="imageCodeDisplayId" width="180" height="50" ng-src="mysite.com/wp-content/uploads/img.jpg" alt="Verify Image" style="padding:2px;border-style:solid;border-width:1px;border-color:#CCC;margin-top:5px;margin-bottom:5px" src="mysite.com/wp-content/uploads/img.jpg"> <a class="glyphicon glyphicon-repeat" aria-hidden="true" title="Reload" style="cursor:pointer;font-size:30px;top:10px;left:10px;text-decoration:none" ng-click="getCaptcha()"></a> </div>

You can use document.getElementById('imageCodeDisplayId').src to access the src attribute of the img element.

You can use the ExecutScriptAsync() method to retrieve the value via C#.

Here you go:

// get the src attribute value
string srcAttributeValue = await webView21.CoreWebView2.ExecuteScriptAsync("document.getElementById('imageCodeDisplayId').src");

// show it in a message box
MessageBox.Show(srcAttributeValue);

JavaScript code can be injected into WebView2 controls at runtime using host apps. The injected JavaScript applies to all new top-level documents and any child frames. The JavaScript injected into the page is executed at a precise point in time.

You can use the following java script to select src attribute of specified img tag and then show it in an alert:

alert(document.getElementById('imageCodeDisplayId').attributes['src'].value);

So in your WevView2's EnsureHttps use something like the following code:

void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
{
    webView.CoreWebView2
        .ExecuteScriptAsync(@"alert(document.getElementById('imageCodeDisplayId').attributes['src'].value);");
    args.Cancel = true;
}

Output:

js的输出

All extra necessary information is available at Get started with WebView2 in WinForms apps

And also WebView2.ExecuteScriptAsync(String) Method describes everything that you need to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM