Geb Programmer : User Agent Spoofing

As often happens on the internet there is already a website to answer your question. If you would like to know what’s your user agent just visit whatsmyuseragent.comWhat's my user agent

If you run Geb with PhantomJs your user agent will identify you as running PhantomJs. You may be blocked because of that. Fortunately it is easy to change the user agent of PhantomJs driver as illustrated in the next GebConfig.groovy file:

import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.firefox.FirefoxDriver
import org.openqa.selenium.phantomjs.PhantomJSDriver
import org.openqa.selenium.remote.DesiredCapabilities

def capabilities = new DesiredCapabilities()
String fakeUserAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:37.0) Gecko/20100101 Firefox/37.0'
capabilities.setCapability('phantomjs.page.settings.userAgent', fakeUserAgent)

environments {

    chrome {
        driver = { new ChromeDriver() }
    }

    firefox {
        driver = { new FirefoxDriver() }
    }

    phantomJs {
        driver = { new PhantomJSDriver() }
    }

}

If you run with Geb Environment set to PhantomJs then this test will pass:

package groovycalamari.gebwebbot.whatismysuseragent

import geb.Browser
import spock.lang.IgnoreIf
import spock.lang.Specification

class WhatIsMyUserAgentSpec extends Specification {

    @IgnoreIf( { System.getProperty('geb.env') != 'phantomJs' } )
    def "tests phantomJS uses firefox as user agent as set in GebConfig"() {
        when:
        Browser browser = new Browser()

        def ua
        browser.drive(baseUrl: 'https://www.whatismybrowser.com/') {
            to WhatIsMyUserAgentPage
            ua = userAgent
        }
        then:
        ua
        ua.indexOf('PhantomJS/') == -1
        ua.indexOf('Firefox/') != -1
    }
}

I have a Github repository with this code example.

Do you like to read about Geb development? Yes, then Subscribe to Groovy Calamari a weekly curated email newsletter about the Groovy ecosystem which I write 

Leave a Reply

Your email address will not be published. Required fields are marked *