Blocking Request On PhantomJS

- 1 answer

Say I have a page.onResourceRequested(request) function on a PhantomJS script. How can I block the request depending on some value in the request?



Oh, I just figured it out. onResourceRequest can take two arguments, first is requestData and the second is networkRequest, which allows for operations on the request.

Quote from PhantomJS API documentation:

This callback is invoked when the page requests a resource. The first argument to the callback is the requestData metadata object. The second argument is the networkRequest object itself.

The networkRequest object contains these functions:

abort() : aborts the current network request. Aborting the current network request will invoke onResourceError callback.

changeUrl(newUrl) : changes the current URL of the network request. By calling networkRequest.changeUrl(newUrl), we can change the request url to the new url. This is an excellent and only way to provide alternative implementation of a remote resource. (see Example-2)

setHeader(key, value)