Opening a page containing a connection with CasperJs / PhantomJs

I have a page that opens a websocket ( connection on a node.js server.

For testing purposes, I want to open a page with a non-browser browser using CasperJs (I also tried pure PhantomJs with the same result).

Open connection using Chrome always works. An open connection using CasperJs always works (at least the corresponding callbacks are executed on the client and server).
Messaging (socket.emit) using Chrome always works.
Messaging (socket.emit) using CasperJs sometimes works.

I get the same behavior when I configure to use poll only instead of websocket. I know that "sometimes" is not very accurate, but I haven't found the "patter" yet when it happens.

Have you used a non-browser browser to successfully open the page with Do you have any hints what might be the reason?

Additional Information:

My client performs

var socket = io.connect('http://localhost:3000');


After that, the connection method is called on the server (it prints the transport type and socket id for debugging):

io.on('connection', function (socket) {
     console.log('Client connect ('+ +'): ' +;


The result is the same as expected ( uses XHR first and then updates to websocket):

Client connect (XHR): d-moyZ_D6Z6eG7SNAAAA


Also the connection callback is executed on the client side:

socket.on('connect', function () {
   console.log("Client successfully connected to data server. Transport type: " +;


The output on the client console is expected:

Client successfully connected to data server. Transport type: XHR


If I am using a regular browser, I can exchange messages without problems. If I use my casper script then messaging works sometimes . Most of the time nothing happens when I call socket.emit. The cash register script is pretty simple. I had a feeling it might be a sync issue, so I created a wait for the javascript resource that makes the connection, unchanged:

casper = require('casper').create({
    verbose: true,
    logLevel: "debug"

casper.start('page.html', function() {

casper.waitForResource("dataConnection.js", function() {
    this.echo(' has been loaded.');
    this.wait(14000, function() {
        this.echo("I've waited for some seconds.");

casper.on('remote.message', function(message) {


Disable callbacks on the client / server also run as expected. You can see that upgrading to websocket worked:

Client disconnect (WebSocket): d-moyZ_D6Z6eG7SNAAAA connectionCount: 0




source to share

All Articles