vb.netseleniumgoogle-chromeselenium-chromedriverchrome-web-driver

Going to a different web page within the same window without closing the VB.Net Selenium Chrome window


Dear members of the forum.

With the code below, I can open the chrome web browser using selenium and go to the internet address I want. I have only one problem. When I click on button1, the chrome window opens and goes to http://google.com/. When I click button2 while the driver is on, it runs a separate chrome driver and goes to yahoo. this is what i want After opening the first chrome window and entering google, when I click BUTTON2 "WITHOUT OPENING NEW CHROME" I want it to go to yahoo.com from the EXISTING CHROME WINDOW .. I could not find the code. I want to go to another link without closing the current chrome engine. where am I making a mistake? I ask for your help. respects.

Imports OpenQA.Selenium
Imports OpenQA.Selenium.Chrome
Imports OpenQA.Selenium.Support.UI
Imports System.Text

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim driver As IWebDriver
        driver = New ChromeDriver()
        driver.Navigate().GoToUrl("http://google.com/")

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim driver As IWebDriver
        driver = New ChromeDriver()
        driver.Navigate().GoToUrl("http://yahoo.com/")
    End Sub
End Class

Solution

  • You probably should be using a shared instance of driver which would reuse the existing one you create upon pressing the first button.

    This untested code shows how this could work:

    Public Class Form1
        Dim driver As IWebDriver
    
        Private Sub DoNavigate(address As String)
            If (driver Is Nothing) Then
                driver = New ChromeDriver()
            End If
            driver.Navigate().GoToUrl(address)
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            DoNavigate("http://google.com/")
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            DoNavigate("http://yahoo.com/")
        End Sub
    End Class
    

    The buttons now both call DoNavigate in order to cause the URL change.

    The DoNavigate function:

    1. Checks whether driver has already been created.
    2. Creates driver if it has not been created.
    3. Navigates to the address specified.