0 Replies - 5229 Views - Last Post: 03 March 2014 - 02:18 PM

#1 andrewsw   User is online

  • never lube your breaks
  • member icon

Reputation: 6819
  • View blog
  • Posts: 28,257
  • Joined: 12-December 12

WebBrowser Control Nuggets

Post icon  Posted 03 March 2014 - 02:18 PM

    WebBrowser1.Navigate("http://www.somepage.com")    'or
    WebBrowser1.Navigate(New Uri("http://www.somepage.com"))
    'display from text-file (resource) or string
    WebBrowser1.DocumentText = My.Resources.TextFile1
    WebBrowser1.DocumentText = "<html><body><h1>My email</h1></body></html>"
    'clicking a button
    'to follow a hyperlink (an a-link) extract its href attribute 
    'and use WebBrowser.Navigate(href)

    'adding text to an input element
    WebBrowser1.document.GetElementById("the_id").InnerText = "whatever.."

Most code runs, or is called from, the DocumentCompleted event:
    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As _ 
            WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted

        If WebBrowser1.Url.ToString.Contains("bbc") Then
            MessageBox.Show("The BBC!")
        End If
    End Sub

..although, it is possible to check if the document is loaded:
    Dim doc = WebBrowser1.Document
    If doc IsNot Nothing Then
        'the page is available..
        '(use DocumentCompleted event in preference)
    End If

GetElementsByTagName and GetAttribute:
    'finds all a-tags in the page reading their href attribute
    Dim addresses As String = ""
    Dim pageElements As HtmlElementCollection = WebBrowser1.document.GetElementsByTagName("A")
    'or WebBrowser1.document.All
    For Each currElement As HtmlElement In pageElements
        addresses &= currElement.GetAttribute("href") & vbNewLine

If you know the ID of an element:
    Dim elem As HtmlElement = WebBrowser1.document.GetElementById("someId")
    'if you know the id or name of a form you can use:

Otherwise use GetElementsByTagName, document.All. some_element.All, some_element.Children, etc., and either refer to an element by its index (3) or iterate the collection:
    Dim elems As HtmlElementCollection

    elems = WebBrowser1.document.GetElementsByTagName("INPUT")
    Dim elem4 As HtmlElement = elems(3)     'the fourth input
    Dim elem4Name As String = elem4.GetAttribute("name")

Removing an element:
    Dim pageElements As HtmlElementCollection = WebBrowser1.document.GetElementsByTagName("input")
    For Each currElement As HtmlElement In pageElements
        If currElement.GetAttribute("type").ToLower = "submit" Then
            currElement.OuterHtml = ""
        End If

Prevent opening of new window:
    Private Sub WebBrowser1_NewWindow(sender As Object, e As System.ComponentModel.CancelEventArgs) _
            Handles WebBrowser1.NewWindow
        e.Cancel = True
    End Sub

Is This A Good Question/Topic? 0
  • +

Page 1 of 1