PhantomJS: specify User Agent when making a call

alberto56 picture alberto56 · Oct 3, 2013 · Viewed 17.5k times · Source

I am using PhantomJS to make calls to a web page, like this:

page.open('http://example.com', function (s) {
  console.log(page.content);
  phantom.exit();
});

I am using this in the context of Drupal Simpletests, which require me to set a special USERAGENT in order to use the test database instead of the real database. I would like to fetch the web page a specific user agent. For example, in PHP with Curl, I can do this with CURLOPT_USERAGENT before making a cUrl call.

Thanks!

Albert

Answer

alberto56 picture alberto56 · Oct 3, 2013

I found the answer in the useragent.js file in the phantomjs examples directory:

var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var ua = page.evaluate(function () {
            return document.getElementById('myagent').innerText;
        });
        console.log(ua);
    }
    phantom.exit();
});