Remotely debug PhantomJS

If you need to nicely debug a page in PhantomJS you can use remote debugging feature.

First you have to create a file test.js with following contents: require('webpage').create().open("http://localhost/yourproject.html"); Now you do:

  1. Run in terminal phantomjs --remote-debugger-port=9000 test.js
  2. Open in browser (ex. Chrome) page localhost:9000
  3. There should be a link with title about:page - follow that link
  4. A remote debugger (similar to Chrome) will open as a page. Type in its console (bottom left icon) __run() and run it (press enter)
  5. Open again localhost:9000 in a new tab, now you should see one more link - follow it
  6. You opened the debugger for your page

If you want to set breakpoints before page will run then replace your test.js contents with:

page = require('webpage').create();
page.open('http://localhost/tmp/hammer.js/tests/unit/', function(){
  debugger;  // this is necessary
  page.evaluate(function() {
    setTimeout(function(){
      debugger;
      window.callPhantom('done');
    }, 0);
  });
});

Now you do:

  1. Run in terminal phantomjs --remote-debugger-port=9000 test.js
  2. Open in browser (ex. Chrome) page localhost:9000
  3. There should be a link with title about:page - follow that link
  4. A remote debugger (similar to Chrome) will open as a page. Type in its console (bottom left icon) __run() and run it (press enter)
  5. Open again localhost:9000 in a new tab, now you should see one more link - follow it
  6. Go back to first tab and continue script execution (it should be stopped at debugger point)
  7. Go back to second tab and set your desired break points. When you set them continue script execution (it should be stopped at debugger point)
  8. Now inspect your code.