Is there a way to intercept a resource request and give it a response directly from the handler? Something like this:
page.onRequest(function(request){
request.reply({data: 123});
});
My use case is for using PhantomJS to render a page that makes calls to my API. In order to avoid authentication issues, I'd like to intercept all http requests to the API and return the responses manually, without making the actual http request.
onResourceRequest
almost does this, but doesn't have any modification capabilities.
Possibilities that I see:
- I could store the page as a Handlebars template, and render the data into the page and pass it off as the raw html to PhantomJS (instead of a URL). While this would work, it would make changes difficult since I'd have to write the data layer for each webpage, and the webpages couldn't stand alone.
- I could redirect to
localhost
, and have a server there that listens and responds to the requests. This assumes that it would be ok to have an open, un-authenticated version of the API onlocalhost
. - Add the data via
page.evaluate
to the page's globalwindow
object. This has the same problems as #1: I'd need to know a-priori what data the page needs, and write server side code unique to each page.