Jlil
Jlil

Reputation: 331

vb.net WebBrowser Open link in default browser

I want to show image ads in my program, I use the Web Browser tool and put a link advertising. I want to open ads links in the user's default browser.

In Web Browser "URL" I use : "http://name.com/ads.html#num1"

and this "num1" is :

<div id="num1">
    <a href="http://google.com" target="_blank"> 
        <img src="img/num1.png" />
    </a>
</div>

I need to open this link in default browser.

Upvotes: 0

Views: 4237

Answers (2)

Eldar Gerfanov
Eldar Gerfanov

Reputation: 41

I know this has been a long time but expanding on Andrea's answer i made it work for all URLs this way:

Private docComplete As Boolean = False
    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        docComplete = True
    End Sub

Private Sub WebBrowser1_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser1.Navigating
    If docComplete Then
        ' Process.Start(e.Url.ToString)
        openULR(e.Url.ToString) 'start process by a default browser
        e.Cancel = True
    End If
End Sub

just to make sure links trigger the event i replace _blank tags in html to _self like this:

 html = Replace(html, "target=""_blank""", "target=""_self""")

Upvotes: 1

Andrea
Andrea

Reputation: 12355

You can use WebBrowser's Navigating event and try to cancel the event redirecting it to the default browser.

Problem is this event occurs every time a webpage is loaded in WebBrowser control. To avoid redirection on each navigating event you could filter on target url (if this is an acceptable solution for you):

Private Sub WebBrowser1_Navigating(sender As Object, e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles WebBrowser1.Navigating
    If e.Url.ToString = "http://google.com/" Then
        Process.Start(e.Url.ToString)
        e.Cancel = True
    End If
End Sub

In order for this solution to work you also have to change your html page switching target from _blank to _self otherwise Navigating error wouldn't be triggered:

<a href="http://google.com" target="_self"> 
    <img src="img/num1.png" />
</a>

Upvotes: 1

Related Questions