chromedp: How to get the URL of the current page

In the previous article, we developed a simple application and open google.com with chromedp. in this article we are going to take a look and one of the chromedp functionalities to deal with the page and URL.

The way that the developers decided to use to do that is a very popular way along with the golang developers, Passing the reference of a variable to the function. I see the same pattern a lot in go libraries, for example, GORM also using the same pattern.

In today’s scenario, we want to open the chromedp Github page and go to one of the files inside the repository and print the URL of the page. Simple and easy! so let’s get started!!!

For this purpose, we need to select the element that we want to click on it. Remember we just want to make things that we do manually, automatically. it means if we want to open the file named util_test.go, first, we need to go to the URL github.com/chromedp/chromedp then find the file inside the list and then click on it. For finding the elements inside the page we can simply use CSS Selectors.

// our selector to find the file inside the page.
selector := "a[title='util_test.go']"
tasks := chromedp.Tasks{
  // go to the page
    chromedp.Navigate("https://github.com/chromedp/chromedp"),
  // wait until the elemnt is visible and available inside the page
    chromedp.WaitEnabled(selector),
  // do a click on it
    chromedp.Click(selector),
}

so we already go to the page that we wanted the only step that still remains is getting the page URL. For this purpose, we define a string variable and pass it to the Location function of chromedp.

var u string
...
chromedp.Location(&u),

and here's the complete code:

package main

import (
    "context"
    "fmt"

    "github.com/chromedp/chromedp"
)

func main() {
    var u string
    opts := append(
        // select all the elements after the third element
        chromedp.DefaultExecAllocatorOptions[3:],
        chromedp.NoFirstRun,
        chromedp.NoDefaultBrowserCheck,
    )
    // create chromedp's context
    parentCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
    defer cancel()

    selector := "a[title='util_test.go']"
    tasks := chromedp.Tasks{
        chromedp.Navigate("https://github.com/chromedp/chromedp"),
        chromedp.WaitEnabled(selector),
        chromedp.Click(selector),
        chromedp.Location(&u),
    }
    ctx, cancel := chromedp.NewContext(parentCtx)
    defer cancel()
    if err := chromedp.Run(ctx, tasks); err != nil {
        panic(err)
    }
    fmt.Printf("URL => %s\n", u)
}

the output is:

URL => https://github.com/chromedp/chromedp/blob/master/util_test.go

No Comments Yet