user399421
user399421

Reputation: 857

How to disable external javascript execution / site requests in phantomjs

I am trying to run some tests on a website looking for issues.

For the record, I am using phantomjs with the ghostdriver in selenium from C#

Everything is working fine, but I would like to speed things up. Checking on the headers in fiddler, a lot of time is spent on external calls to external sites (facebook / twitter) for the social plugins all sites seem to think is a good idea these days :-\

I am not required to test these functions, so am trying to disable external site calls, which should speed my tests up some what.

Is there a way in phantom to get the effect that noscript / ghostery gives in firefox?

Upvotes: 4

Views: 1815

Answers (1)

Cybermaxs
Cybermaxs

Reputation: 24558

To filter invalid requests, you could use the onResourceRequested callback : this allow you to abort unwanted urls.

Here is a basic example for stackoverflow.

var system = require('system');
var page = require('webpage').create();
var domain = 'stackoverflow.com'
var url = 'http://www.stackoverflow.com';

page.onResourceRequested = function (requestData, networkRequest) {
    if (requestData.url.indexOf('.js')===-1 && requestData.url.indexOf(domain) === -1) {
        networkRequest.abort();
        console.log('aborted :'+ requestData.url)
    }
};

page.onResourceReceived = function (response) {
    console.log('Response (#' + response.url + ', stage "' + response.stage + '"): ');
};

if (system.args.length !== 1) {
    console.log("Usage: phantomjs filter.js url");
} else {
    page.open(url, function (status) {
        if (status = 'succeed') {
            console.log("status", status);
            phantom.exit(0);
        }
    });
}

Note that it's not recommended to abort js files, as this can cause a javascript error on you page.

Another way to speed up your test is to disable images using argument --load-images=false

Upvotes: 2

Related Questions