Bacancy Bacancy
  • Customers

      Fortune 500 Clients

      Verizon
      Verizon
      Franklin Templeton
      Franklin Templeton
      The Container Store
      The Container Store
      KPMG
      KPMG
      AdviceWorks
      AdviceWorks
      Bridgestone
      Bridgestone
      NatWest Markets
      NatWest Markets
      Shell
      Shell
      Bangkok Bank Ltd
      Bangkok Bank Ltd
      The Children's Place
      The Children's Place
      Edward Jones
      Edward Jones
      United Parcel Service
      United Parcel Service
      Academy Sports & Outdoors
      Academy Sports & Outdoors

      Case Studies

      React JS VueJS Angular JS React Native Flutter Full Stack
      Ruby on Rails Node JS Golang AI & ML Data Science Java
      Python Salesforce DevOps Block Chain Mobile App Embedded & Hardware

      Industries

      Information Technology BFSI Education Marketing & Advertising Manufacturing Retail Logistics & Transportation
      Healthcare eCommerce Public Services Travel & Hospitality Cloud Telecommunications Real Estate
      Explore All
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      UK

      +44 127 479 2316
  • what we do

      Experience

      Digital Workplace Services Product Enhancement

      Insights

      AI & Automation Data Analytics

      SAP Solutions

      SAP Consultation

      Innovate

      Robotic Process Automation Software Engineering Services Internet of Things (IoT) Data Science Artificial Intelligence Machine Learning

      Accelerate

      Cloud - Bacancy Combat Digital Process Automation Open Source Microsoft Dynamics Salesforce

      Assure

      Quality Assurance IT Staff Augmentation

      Embedded & Hardware

      Product Engineering Analog Design Services FPGA Engineering Service Wireless Design Embedded Software Design

      not list

      Hardware Engineering Power Engineering IoT Hardware
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      UK

      +44 127 479 2316
  • who we work with

      Industries

      Banking Financial services & Insurance Startups Oil & Gas

      not list

      Healthcare Life Science Real Estate & Construction Logistics
      bacancy

      Let’s grow together Partner with us

      get quote
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      UK

      +44 127 479 2316
  • about us

      Culture

      Agile Mindset Bacancy Values Bacancy Culture

      About Company

      About Us Leadership Team Awards & Recognition Infrastructure

      not list

      Customer Reviews Our Locations Partnership Media Coverage

      WE ARE

      GREAT PLACE TO WORK - CERTIFIEDTM

      Building and sustaining High-Trust, High-Performance CultureTM

      Bacancy Great Place to Work
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      UK

      +44 127 479 2316
  • technology

      Front End

      Angular Reactjs Vue.js UI/UX

      Platforms

      MS Dynamics Salesforce

      Back End

      Ruby on Rails Node.js Golang Laravel .NET Java Python

      Mobile

      React Native Flutter Android iOS

      Cloud

      AWS DevOps

      QA

      Automation Testing Software Testing

      Embedded & Hardware

      Embedded
      bacancy

      World-class expertise,Delivered

      get quote
      Explore All
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      UK

      +44 127 479 2316
  • PRODUCTS

      EV Products

      Battery Management System Motor Controller AC Charger Explore All

      not list

      CCS2 Controller DC Fast Charger AC Charge Controller
      bacancy

      Let’s grow together Partner with us

      get quote
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      UK

      +44 127 479 2316
hire developers

Bacancy

Bacancy represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.

12+

Countries where we have happy customers

1050+

Agile enabled employees

06

World wide offices

12+

Years of Experience

05

Agile Coaches

14

Certified Scrum Masters

1000+

Clients projects

1458

Happy customers

  • Customers
      Case Studies
      • React JS
      • Angular JS
      • Vue JS
      • Node JS
      • AI & ML
      • Explore All
      Fortune 500 Clients
      • Verizon
      • The Container Store
      • KPMG
      • Academy Sports & Outdoors
      • Bangkok Bank Ltd
      • The Children's Place
      • Edward Jones
      • Franklin Templeton
      • AdviceWorks
      • NatWest Markets
      • Bridgestone
      • United Parcel Service
      Industries
      • Information Technology
      • BFSI
      • Education
      • Marketing & Advertising
      • Manufacturing
      • Retail
      • Logistics & Transportation
      • Healthcare
      • eCommerce
      • Public Services
      • Travel & Hospitality
      • Cloud
      • Telecommunications
      • Real Estate
  • What we do
      Experience
      • Digital Workplace Services
      • Product Enhancement
      Insights
      • AI & Automation
      • Data Analytics
      SAP Solutions
      • SAP Consultation
      Innovate
      • Blockchain
      • Software Engineering Services
      • Internet of Things (IoT)
      Accelerate
      • Cloud - Bacancy Combat
      • Digital Process Automation
      • Open Source
      • Microsoft Dynamics
      • Salesforce
      • Service Experience Transformation
      Assure
      • Testing
      • Resource Augmentation
      Embedded & Hardware
      • Product Engineering
      • Analog Design Services
      • FPGA Engineering Service
      • Wireless Design
      • Embedded Software Design
      • Hardware Engineering
      • Power Engineering
      • IoT Hardware
      • AL/ML
  • who we work with
      Industries
      • Banking Financial services & Insurance
      • Startups
      • Oil & Gas
      • Healthcare Life Science
      • Real Estate & Construction
      • Logistics
  • About Us
      About Company
      • About Us
      • Leadership Team
      • Awards & Recognition
      • Infrastructure
      • Our Locations
      • Partnership
      Culture
      • Agile Mindset
      • Bacancy Values
      • Bacancy Culture
  • Technology
      Front End
      • Angular
      • Reactjs
      • Vue.js
      • UI/UX
      Platforms
      • MS Dynamics
      • Salesforce
      Back End
      • Ruby on Rails
      • Node.js
      • Golang
      • Laravel
      • .NET
      • Java
      • Python
      Mobile
      • React Native
      • Flutter
      • Android
      • iOS
      Cloud
      • AWS
      • DevOps
      QA
      • Automation Testing
      • Software Testing
      Embedded & Hardware
      • Embedded
      Explore All
  • Products
    • Battery Management System
    • Motor Controller
    • CCS2 Controller
    • AC Charger
    • DC Fast Charger
    • AC Charge Controller
    • Explore All
  • Careers
  • Work @ Bacancy
  • Blogs
  • Resources
  • Customer Reviews
  • Contact
  • Get Quote
Use Headless Chrome in Golang with Godet

How to Use Headless Chrome in Golang with Godet

Ashvin Kumbhani
Ashvin Kumbhani Full Stack Developer
Last Updated on January 2, 2023 | Written By: RadhaKotecha
December 30, 2019 5 min read

So many times it happens when we have to test a few cases at the time of development to ensure it is the same as provided on the website. It also happens when we have to fill up the lengthy, tedious, and monotonous form. I encountered this problem while filling up the contact us form at the time of enquiring about a car.

They ask too many questions which the customer had already filled up previously in the application for other dealers. If you have the same data in the database, it’s so easy and convenient to fill the form as I had that same data in my database. I was able to make the form fill up faster by opening up a golang headless chrome instance in my server. And then, I used Golang and godet to access the website, fill-up the way and get the contract printed as a pdf on my server saving the user an ample amount of time with the tedious process of filling up the form. So let me tell you how to do it.

The Procedure

Pre-installed:

  • Golang
  • chromium-browser

We will be going to navigate from Google.com to search some text and then screenshot and print the very first link of the search.

First, let us start by creating a primary go code that just prints out, “Hey All.”

So create a file that satisfies you GOPATH.

FileName: main.go

package main
 
import (
    "log"
)
 
func main() {
    log.Println("Hey All!")
}

Now let us open up chromium-browser by code and kill the process after waiting 2 minutes.

package main
 
import (
    "log"
    "os/exec"
    "time"
)
 
func main() {
    chromeapp := "chromium-browser"
    chromeappArg := []string{"--headless", "--hide-scrollbars", "--remote-debugging-port=9222", "--disable-gpu", "--allow-insecure-localhost"}
    cmd := exec.Command(chromeapp, chromeappArg...)
    err := cmd.Start()
    if err != nil {
        log.Println("cannot start browser", err)
    }
 
    time.Sleep(2 * time.Minute)
 
    killapp := "kill"
    killappArg := []string{"$(lsof -t -i:9222)"}
    cmd = exec.Command(killapp, killappArg...)
    err = cmd.Start()
    if err != nil {
        log.Println("cannot kill processes", err)
    }
}

Now in the 30-second sleep, if you open up another terminal and run lsof -i:9222, this will show you that the chromium-browser has now started and the dev-tools are running on port 9222.

 running on port 9222.

You can see the tabs of the chromium-browser we created on localhost:9222

chromium-browser

If you click on the about: blank, you’ll be able to see the process that we do on the opened tab in our chromium-browser.

Before connecting to chromium, we will need to install godet.

So on your terminal run, go get “github.com/raff/godet”.

Do you need assistance to solve your Golang error?
Hire Golang developer from us to fix the bugs and fine-tune your Golang app user experience.

This package creates a small layer between the google chrome dev tools and Golang.

Now we will navigate to www.google.com to do so add the following code.

package main
 
import (
    "log"
    "os/exec"
    "time"
 
    "github.com/raff/godet"
)
 
func main() {
    chromeapp := "chromium-browser"
    chromeappArg := []string{"--headless", "--hide-scrollbars", "--remote-debugging-port=9222", "--disable-gpu", "--allow-insecure-localhost"}
    cmd := exec.Command(chromeapp, chromeappArg...)
    err := cmd.Start()
    if err != nil {
        log.Println("cannot start browser", err)
    }
 
    // Will wait for chromium to start
    time.Sleep(5 * time.Second)
 
    // connect to Chromium instance
    remote, err := godet.Connect("localhost:9222", true)
    if err != nil {
        log.Println("cannot connect to Chrome instance:", err)
        return
    }
 
    // disconnect when done
    defer remote.Close()
 
    remote.PageEvents(true)
    remote.DOMEvents(true)
 
    _, err = remote.Navigate("https://www.google.com")
    if err != nil {
        log.Println("cannot connect to Chrome instance:", err)
        return
    }
 
    time.Sleep(30 * time.Second)
 
    killapp := "kill"
    killappArg := []string{"$(lsof -t -i:9222)"}
    cmd = exec.Command(killapp, killappArg...)
    err = cmd.Start()
 
    if err != nil {
        log.Println("cannot kill processes", err)
    }
}

The remote, err:= godet.Connect(“localhost:9222”, true) will connect to the chromium-browser and the line defer remote.Close() will close the connection on the full execution of our code. This is preferable to do so that we can prevent memory leaks.

The remote.PageEvents(true) remote.DOMEvents(true) will log all the PageEvents and DomEvents on our terminal.

_, err = remote.Navigate(“https://www.google.com“) this is the magic code that navigates the tab open in chromium-tab to www.google.com.

google

Now we are going to use the EvaluateWrap function to inject JS in the browser.

For more such functions, you can refer to https://github.com/raff/godet.

We will count the times that the page stops loading and inject js based on it.

package main
 
import (
    "log"
    "os/exec"
    "time"
 
    "github.com/raff/godet"
)
 
func main() {
    chromeapp := "chromium-browser"
    chromeappArg := []string{"--headless", "--hide-scrollbars", "--remote-debugging-port=9222", "--disable-gpu", "--allow-insecure-localhost"}
    cmd := exec.Command(chromeapp, chromeappArg...)
    err := cmd.Start()
    if err != nil {
        log.Println("cannot start browser", err)
    }
 
    // Will wait for chromium to start
    time.Sleep(5 * time.Second)
 
    // connect to Chromium instance
    remote, err := godet.Connect("localhost:9222", true)
    if err != nil {
        log.Println("cannot connect to Chrome instance:", err)
        return
    }
 
    // disconnect when done
    defer remote.Close()
 
    remote.PageEvents(true)
    remote.DOMEvents(true)
 
    _, err = remote.Navigate("https://www.google.com")
    if err != nil {
        log.Println("cannot connect to Chrome instance:", err)
        return
    }
 
    count := 0
 
    remote.CallbackEvent("Page.frameStoppedLoading", func(params godet.Params) {
        count = count + 1
        log.Println("TCL: remote.CallbackEvent -> count", count)
        switch count {
        case 1:
            _, err = remote.EvaluateWrap(`
                document.getElementsByClassName('gLFyf gsfi')[0].value = "Bacancy Technology"
                document.getElementsByClassName('gNO89b')[1].click()
            `)
            if err != nil {
                log.Println("Error executing js block 1:", err)
                return
            }
            time.Sleep(5 * time.Second)
        case 2:
            _, err = remote.EvaluateWrap(`
                document.getElementsByClassName('LC20lb')[0].click()
            `)
            if err != nil {
                log.Println("Error executing js block 1:", err)
                return
            }
            time.Sleep(5 * time.Second)
            // take a screenshot
            _ = remote.SaveScreenshot("SearchResultScreenshot.png", 0644, 0, true)
                // print a pdf
                err = remote.SavePDF(`./SearchResultPdf.pdf`, 0644)
                if err != nil {
                    log.Println("Error saving pdf.")
                }
            }
    })

    time.Sleep(30 * time.Second)
 
    killapp := "kill"
    killappArg := []string{"$(lsof -t -i:9222)"}
    cmd = exec.Command(killapp, killappArg...)
    err = cmd.Start()
    if err != nil {
        log.Println("cannot kill processes", err)
    }
}

Explaining what we have done based on cases

Case 1: Fill up the Google search box with “Bacancy Technology and clicking the search button.
Case 2: Clicking the first link and screenshotting and printing the link opened

When you run go run main.go after navigating to the file in your terminal, after 30 seconds, you’ll be able to see 2 files generated in the same directory.

I’ll attach the screenshot for the look of the browser(the one in localhost:9222), the screenshot created, and the pdf generated.

Browser:

Browser

Screenshot:

pdf generated


Expand Your Digital Horizons With Us.

Start a new project or take an existing one to the next level. Get in touch to start small, scale-up, and go Agile.


Or
E-mail us : [email protected]

Your Success Is Guaranteed !

Related Articles

ChatGPT with GO Apps
Mahendra Kadam

June 12, 2023

Golang

Next-Gen Application Development Using ChatGPT in GO Apps

By : Mahendra Kadam

In this blog, we are putting forward an idea - what happens if we decide to use ChatGPT in GO apps? We intend to explore...

< 1 Minute Read
Read More
SaaS Applications With Golang
Dipal Bhavsar

May 8, 2023

Golang

Unlock the Power of SaaS Applications With Golang

By : Dipal Bhavsar

Quick Summary: Building a SaaS application is increasingly popular because of its scalability, flexibility, and cost-effectiveness. Golang is an outstanding programming language for SaaS apps,...

9 Minute Read
Read More
golang grpc
Paridhi Wadhwani
Kishan Dekivadiya

April 14, 2023

Golang

Creating a Golang gRPC Service: Step-by-Step Tutorial

By : Paridhi Wadhwani & Kishan Dekivadiya

Quick Summary: This tutorial enables you to understand and learn about Golang gRPC service. Using Go programming language, get the step-by-step points to create a...

5 Minute Read
Read More

How Can We Help You?

india India (HQ)

Corporate House
15-16, Times Corporate Park, Thaltej, Ahmedabad, Gujarat 380059

USA USA

601 Brickell Key Drive, Suite 700, Miami, Florida, 33131, USA

canada Canada

71 Dawes Road, Brampton, On L6X 5N9, Toronto

australia-flag Australia

351A Hampstead Rd, Northfield SA 5085

UAE UAE

1608 Clover Bay, Business Bay, Dubai, UAE. PO Box 62049

sweden Sweden

Junkergatan 4, 126 53 Hagersten


Get in Touch

call-yellow-icon

Contact Number

+1 347 441 4161

gmail-icon

Email Us

[email protected]


  • Employee
  • Brochure
  • Quality Assurance
  • Resources
  • Privacy Policy
  • Sitemap
  • Solutions
  • Careers
  • Testimonials
  • Tutorials
  • QandA
  • Contact Us
  • bacancy google review 4.6
    bacancy google review
    bacancy glassdoor review 4.5
    bacancy glassdoor review
    bacancy clutch review 4.8
    bacancy clutch review
    bacancy goodfirms review 4.5
    bacancy goodfirms review
    iso
    X

    Get Our Newsletter

    Be The First To Get The Latest Updates And Tutorials.

    Request A Free Consultation