Search code examples
requestphantomjshtmlabort

How to stop/abort/cancel a page load in PhantomJS?


I use PhantomJS to check a list of links for specific content. Once these content is found I would like to cancel the page load to avoid further ressource requests and continue with the next page to improve speed.

I filter requests in page.onResourceRequested and request.abort(); everything that doesn't match but that doesn't prevent PhantomJS from requesting till the site finished.

Tried page.stop(); -> crashes PhantomJS

The documentation seems lacking and I wonder if there is a command I can use to do that. I can't use page.close(); because I need the page object after the content is found.


Solution

  • page.onResourceRequested = function(requestData, request) {
        var matchUrlNeeded = ((/someregexforurl\/js/g).test(requestData.url));
        if (matchUrlNeeded) {
            doStuffWithTheUrl;
            response.close(); 
            request.abort();
            page.cancel(); }
        }
        else {
            //console.log("NO MATCH : " + requestData.url); request.abort(); } { }