Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change selenium user agent in selenium-webdriver nodejs land?

I'm in javascript + mocha + node land.

I have tried setting userAgent and 'user-agent' as keys on capabilities:

var webdriver = require('selenium-webdriver');
var ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X)';

var driver = new webdriver.Builder().
     ...
     withCapabilities({ 'browserName': 'firefox',
        userAgent: ua,
        'user-agent': ua,
    }).
    build();

There is this answer which says to use a firefox profile, but that's not exposed. There is no driver.FirefoxProfile nor one exposed globally nor webdriver.FirefoxProfile nor driver.profiles etc.

I have tried Googling and looking the source and the documentation but there is nothing on this.

like image 651
Andy Ray Avatar asked Aug 29 '13 02:08

Andy Ray


People also ask

How do I change user Agent in selenium?

To change the user Agent, we shall take the help of ChromeOptions class. Then apply the add_argument method on the object created. We shall pass user-agent and <value of the user Agent> as parameters to that method. Finally, this information shall be passed to the driver object.

How do I find user Agent in selenium?

We can get the user Agent information with Selenium webdriver. This is done with the help of the JavaScript Executor. Selenium executes JavaScript commands with the help of the execute_script method. To obtain the user Agent information, we have to pass the return navigator.


2 Answers

I succesfully changed phantom's user agent using WD with this code:

var capabilities = {
    'browserName': 'phantomjs',
    'phantomjs.page.settings.userAgent':  'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36'
};
return browser
    .init(capabilities)
...

And this link shows how to change firefox's user agent, although the code provided is for C#/Ruby.

like image 73
pyrho Avatar answered Oct 26 '22 23:10

pyrho


You just need to install the firefox-profile package. Here's a snippet:

var webdriver = require('selenium-webdriver');
var FirefoxProfile = require('firefox-profile');

var myProfile = new FirefoxProfile();        
var capabilities = webdriver.Capabilities.firefox();

// here you set the user-agent preference 
myProfile.setPreference('general.useragent.override', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36');

// attach your newly created profile 
myProfile.encoded(function(encodedProfile) {
    capabilities.set('firefox_profile', encodedProfile);

    // start the browser 
    var wd = new webdriver.Builder().
        withCapabilities(capabilities).
        build();

    wd.get('http://testingsite.com/');
});

Easy peasy!

like image 26
gyss Avatar answered Oct 26 '22 23:10

gyss