Rose Rose - 1 year ago 148
C# Question

Prevent WebView to open links in other browsers

I have a webview and I wish that if

, then do not open it in the browser, but remains open in webview.
I tried the code below:

private async void webView_LoadCompleted(object sender, NavigationEventArgs e)
await webView.InvokeScriptAsync("eval", new[]
var hyperlinks = document.getElementsByTagName('a');
for(var i = 0; i < hyperlinks.length; i++)
if(hyperlinks[i].getAttribute('target') != null)
hyperlinks[i].setAttribute('target', '_self');

But there are some websites that can remain open in the webview and there is a website that opens in a browser. How do I fix this so that all links remain open on webview?

Answer Source

Your code didn't work because the "Select" button in your image is a HTML <button> element not a <a> element. When user click this button, it calls JavaScript functions to open in new window. So your code won't work for this scenario.

For handling the new window request, I'd suggest using WebView.NewWindowRequested event. This event occurs when a user performs an action in a WebView that causes content to be opened in a new window. We can provide custom handling of the new window request and set the Handled property to true to prevent the default browser from being launched. Following is a simple sample:

private void webView_NewWindowRequested(WebView sender, WebViewNewWindowRequestedEventArgs args)

    args.Handled = true;

For more info, please see Remarks and Examples in WebView.NewWindowRequested event.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download