Search code examples
seleniumphpunitsaucelabs

How to set a custom user agent using selenium web driver (Sauce Labs)?


I'm running my selenium tests through Sausage (which basically extends the phpunit selenium test case to include additional functionality for Sauce Labs). My issue is I need to run a specific user agent on Firefox.

Here's my firefox browser array:

        array(
            'browserName' => 'firefox',
            'host'        => 'localhost',
            'port'        => 4444,
            'local'       => true,
            'sessionStrategy' => 'isolated'
            )

Solution

  • The trick to getting this is creating a firefox profile which contains the user agent. Then we pass the profile to the web driver as a desired capability.

    The following commands create a firefox profile and base64 encodes it so we can pass it to the web driver.

    mkdir firefox-profile
    cd firefox-profile/
    echo 'user_pref("general.useragent.override", "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25");' >> prefs.js
    zip -r ../firefox-profile.zip *
    base64 < ../firefox-profile.zip
    

    The simplified code with the base64 encoded firefox profile is below:

          array(
                'browserName' => 'firefox',
                'host'        => 'localhost',
                'port'        => 4444,
                'local'       => true,
                'sessionStrategy' => 'isolated'
                'desiredCapabilities' => array(
                    'firefox_profile' => 'UEsDBBQAAAAIAOKTikaRRkklnQAAALQAAAAIABUAcHJlZnMuanNVVAkAAyhPKFUoTyhVVXgEADIE
    MwQljMsOgjAURPd+xU1XkJAWxDYmrNSFJthIgq8dKXjRhoaSAi78elF2MydnZuzRFZ3D2iNPbNEp
    Q8cJqakM1L7ROf1AEgCR9qONUYzTEDydvWyLCeyyC8wZTjmIIipWYHSDIFX1I3cfNl1n8IZlqgfG
    Y0GXArz0cJbHYDb3WDXWhyu6XtuWiele2lIbZFG4jXkIuaqV02z9H3PiJ4svUEsBAhcDFAAAAAgA
    4pOKRpFGSSWdAAAAtAAAAAgADQAAAAAAAQAAALSBAAAAAHByZWZzLmpzVVQFAAMoTyhVVXgAAFBL
    BQYAAAAAAQABAEMAAADYAAAAAAA='
                    )
                )
    

    Thanks to Malvineous from a related thread for the idea: PHPUnit + Selenium: How to set Firefox about:config options?

    For reference, this is the list of allowed desired capabilities: https://code.google.com/p/selenium/wiki/DesiredCapabilities