Question

Can I get an interactive JS debugger working on PhantomJS and/or CasperJS?

Was it helpful?

Solution 2

PhantomJS has a remote-debugger-port option you can use to debug your casper script in Chrome dev tools. To use it, simply execute your casper script with this argument:

casperjs test script.js --remote-debugger-port=9000

Then, open up http://localhost:9000 in Chrome and click on the about:blank link that presents itself. You should then find yourself in familiar Chrome dev tools territory.

Since this is a script and not a web page, in order to start debugging, you have to do one of two things before your script will execute:

  1. In the Chrome dev tools page, open the console and execute __run() to actually start your script.
  2. Insert a debugger; line in your code, and run your casper script with an additional --remote-debugger-autorun=yes argument. Doing so with the remote debug page open will run the script until it hits your debugger; line.

There's a great tutorial that explains this all very nicely.

OTHER TIPS

I didn't solve this entirely, but I definitely reduced the pain.

PhantomJS provides a command line argument to enable webkit's remote debugger. AFAIK, PhantomJS launches a server and dumps the script into the <head> of a webpage with the familiar in-browser debugger. It's actually pretty nice, with breakpoints, etc. However, switching to manually digging around in the terminal for a random command line parameter and the path to your script is seriously irritating.

So, I used IntelliJ's "external tools" feature to launch a Bash script that kills any previous debugging session, launches PhantomJS, and then opens the page up in Chrome.

#!/bin/bash

lsof -i tcp@0.0.0.0:9000 #list anything bound to port 9000
if [ $? -eq 0 ] #if something was listed
    then
        killall 'phantomjs'
fi

/usr/local/Cellar/phantomjs/2.0.0/bin/phantomjs --remote-debugger-port=9000 $1 & 
# --remote-debugger-autorun=yes <- use if you have added 'debugger;' break points
# replace $1 with full path if you don't pass it as a variable.

sleep 2; #give phantomJS time to get started

open -a /Applications/Google\ Chrome.app http://localhost:9000 & #linux has a different 'open' command
# alt URL if you want to skip the page listing
# http://localhost:9000/webkit/inspector/inspector.html?page=1

#see also
#github.com/ariya/phantomjs/wiki/Troubleshooting

The next few lines are settings for IntelliJ, although the above code works just as well on any platform/IDE.

program: $ProjectFileDir$/path/to/bash/script.sh
parameters: $FilePath$
working dir: $ProjectFileDir$

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top