Intercept requests with custom answers in PhantomJS?

Is there a way to intercept a resource request and give it a response directly from the handler? Something like that:

page.onRequest(function(request){
   request.reply({data: 123});
});

My use case is to use PhantomJS to display a page that invokes calls to my API. To avoid authentication issues, I would like to intercept all HTTP requests in the API and return the responses manually without making the actual http request.

onResourceRequest almost does it, but does not have any modification options.

Opportunities that I see:

  • I could save the page as a Handlebars template and display the data on the page and pass it as raw html to PhantomJS (instead of the URL). Although this will work, it will make changes difficult, as I will have to write a data layer for each web page, and web pages cannot be left alone.
  • I could redirect to localhostand have a server there that will listen and respond to requests. This suggests that it would be normal to have an open, non-authenticated version of the API on localhost.
  • Add data through page.evaluateto the global page object window. This has the same problems as # 1: I need to know a priori what kind of data a page needs and write code on the server side, unique to each page.
+4
1

pdf phantom js. , , , .

var page = require('webpage').create(),
  server = require('webserver').create(),
  totallyRandomPortnumber = 29522,
  ...
//in my actual code, totallyRandomPortnumber is created by a java application,
//because phantomjs will report the port in use as '0' when listening to a random port
//thereby preventing its reuse in page.onResourceRequested...

server.listen(totallyRandomPortnumber, function(request, response) {
  response.statusCode = 200;
  response.setHeader('Content-Type', 'application/json;charset=UTF-8');
  response.write(JSON.stringify({data: 'somevalue'}));
  response.close();
});

page.onResourceRequested = function(requestData, networkRequest) {
    if(requestData.url.indexOf('interceptme') != -1) {
        networkRequest.changeUrl('http://localhost:' + totallyRandomPortnumber);
    }
};

phantomjs, /, URL- server.listen page.onResourceRequested. , ( ) .

0

All Articles