0

I want to load a list of URLs in a text file. I have done that using a For Each loop, but I want the browser to load the page first fully before going to the next URL. Here is my code:

For Each url in File.ReadAllLines("urls.txt")
    Browser.Navigate(url)
Next

It doesn't display anything. I tried using:

Do While Browser.ReadyState <> WebBrowserReadyState.Complete
    Application.DoEvents()
Loop

It displays the page but the first line is the only one being loaded.

Blackwood
  • 4,504
  • 16
  • 32
  • 41
Gerard Balaoro
  • 129
  • 2
  • 13

1 Answers1

2

If you want to navigate to each URL after the other you are better of storing all of them in a class level array and subscribing to the WebBrowser.DocumentCompleted event, then keep track of which URL index you're currently at via a class level Integer variable.

When the DocumentCompleted event is raised you just increment the integer variable and load the URL from the next item of the array.

Public Class Form1
    Dim URLs As String()
    Dim UrlIndex As Integer = 0

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        URLs = File.ReadAllLines("urls.txt")
        WebBrowser1.Navigate(URLs(UrlIndex))
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        UrlIndex += 1
        If UrlIndex >= URLs.Length Then
            UrlIndex = 0 'Go back to the beginning.
        End If

        WebBrowser1.Navigate(URLs(UrlIndex))
    End Sub
End Class

To add a delay to it to make each URL show for a little while you can use a Timer (Credit to Werdna for bringing up the subject):

Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
    UrlIndex += 1
    If UrlIndex >= URLs.Length Then
        UrlIndex = 0 'Go back to the beginning.
    End If

    WebBrowser1.Navigate(URLs(UrlIndex))
    Timer1.Stop()
End Sub

Just set the timer's Interval property to change how long a site should be displayed (in milliseconds).

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75