Alex Rivera | Logout

Is there a console for PhantomJS?

Asked 2013-02-23T11:31:28.610
14

I found this on github: https://github.com/gr2m/phantomjs-console

But it is a bit crazy, having to write commands in a file, on one line only, which is then read, and deleted, and the output being in the terminal.

I want a console like...

$ phantomjs --console
phantom> console.log(typeof $)
[Object Function]
phantom> console.log("happy days")
happy days
phantom> 

Is there anything like this?

EDIT: Starting to understand why they did it in such a crazy way...

From PhantomJS-Node: https://github.com/sgentle/phantomjs-node

No really, how does it work?

I will answer that question with a question. How do you communicate with a process that doesn't support shared memory, sockets, FIFOs, or standard input?

Well, there's one thing PhantomJS does support, and that's opening webpages. In fact, it's really good at opening web pages. So we communicate with PhantomJS by spinning up an instance of ExpressJS, opening Phantom in a subprocess, and pointing it at a special webpage that turns socket.io messages into alert() calls. Those alert() calls are picked up by Phantom and there you go!

The communication itself happens via James Halliday's fantastic dnode library, which fortunately works well enough when combined with browserify to run straight out of PhantomJS's pidgin Javascript environment.

If you'd like to hack on phantom, please do! You can run the tests with cake test or npm test, and rebuild the coffeescript/browserified code with cake build. You might need to npm install -g coffeescrip

Edit
Report

1 Answer

5

Well, I ended up writing a wrapper script for the console script I originally linked to: https://github.com/gr2m/phantomjs-console

It is a messy way of doing it, but actually works exactly as I want. Turns out, that phantomjs has plans to handle stdin/stdout but it is not yet implemented. When it is implemented, this crazy method of interacting will become obsolete, and a new, simple script will be able to act as console.

#!/usr/bin/env coffee

sys = require "sys"
fs = require "fs"

# stdin = process.openStdin()
# stdin.addListener "data", (d)-> console.log "you entered: [" + d.toString().substring(0, d.length-1) + "]"

readline = require "readline"

spawn = require("child_process").spawn
phantom = spawn("phantomjs", ["phantom_console.coffee", "http://local/"])

rl = readline.createInterface process.stdin, process.stdout
rl.setPrompt 'phantom> '
rl.prompt()

rl.on 'line', (line)->
  if line == "exit"
    phantom.kill()
    rl.close()
  else
    fs.writeFile ".command.js", line
  # rl.prompt()

rl.on 'close', ->
  phantom.kill()
  process.exit(0)

phantom.stdout.on "data", (data) ->
  console.log data+''
  rl.prompt()

phantom.stderr.on "data", (data) ->
  console.log "\nstderr: " + data
  rl.prompt()

phantom.on "exit", (code) ->
  console.log "child process exited with code " + code
answered 2013-02-23T13:48:13.377

Your Answer