site title as form title and favicon using webbrowser control

ethicalhacker

Well-known member
Joined
Apr 22, 2007
Messages
142
Location
Delhi,India
Programming Experience
5-10
How do I set the form title as the title of the site being visited using a webbrowser, and also how can I set the form icon to the favicon of the site?
Lets say the site being navigated by the webbrowser is google.com then google should appear as the form title and google's logo i.e favicon will show as the form icon.
 
Why not use the DocumentTitleChanged event to set the Text of your form equal to the DocumentTitle?
 
This works for favicon in many cases:
VB.NET:
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) _
Handles WebBrowser1.DocumentCompleted
    Dim web As New Net.WebClient
    Dim fav As String = e.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped) & "/favicon.ico"
    Try
        Dim mem As New IO.MemoryStream(web.DownloadData(fav))
        Me.Icon = New Icon(mem)
    Catch ex As Exception
        Me.Icon = Nothing
    End Try
End Sub
 
Here's some updated favicon code, this uses page linked favicons in preference to site root favicons. The Link code complicates matters a little since you have to look up html elements and attributes, there could be different 'rel' descriptions, there could be relative or absolute links (Uri class handles this well), and the href path could point to Icons or any image format. The code is tested for all variants. Call setFavicon method from DocumentCompleted event.
VB.NET:
Sub setFavicon()
    'from page link
    Dim web As New Net.WebClient
    For Each l As HtmlElement In WebBrowser1.Document.GetElementsByTagName("link")
        If l.GetAttribute("rel").ToLower.Contains("icon") Then
            Dim url As New Uri(l.GetAttribute("href"), UriKind.RelativeOrAbsolute)
            url = New Uri(WebBrowser1.Url, url) 'combines if not href already is absolute
            Try 'download
                Dim mem As New IO.MemoryStream(web.DownloadData(url.AbsoluteUri))
                If IO.Path.GetExtension(url.AbsoluteUri) = ".ico" Then
                    Me.Icon = New Icon(mem)
                Else
                    Dim bmp As New Bitmap(mem)
                    Me.Icon = Icon.FromHandle(bmp.GetHicon)
                    bmp.Dispose()
                End If
                Exit Sub
            Catch ex As Exception
            End Try
        End If
    Next
    'from site root
    Dim fav As String = WebBrowser1.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped) & "/favicon.ico"
    Try 'download
        Dim mem As New IO.MemoryStream(web.DownloadData(fav))
        Me.Icon = New Icon(mem)
    Catch ex As Exception
    End Try
End Sub
 
Back
Top