Kumar Kumar - 7 months ago 30
Javascript Question

PhantomJs: Spawn is not opening any app

I installed phantomJs using npm globally. Why this code isn't working?



var page = require('webpage').create();
var spawn = require('child_process').spawn;

page.open('http://google.com', function(status){
if( status == 'success' ) {
page.render('/tmp/google-snapshot.jpg');
spawn('/usr/bin/sensible-browser', 'file:///tmp/google-snapshot.jpg');
phantom.exit();
}
})





Im using linux mint. Typing command
/usr/bin/sensible-browser file:///example.png
in terminal works fine but why this doesn't work through script.?

Answer

It turns out phantom.exit() was getting called before spawn() can get complete. Below code fixed the problem.

var page  = require('webpage').create();
var spawn = require('child_process').spawn;

page.open('http://google.com', function(status){
  if( status == 'success' ) {
    page.render('/tmp/google-snapshot.jpg');
    spawn('/usr/bin/sensible-browser', 'file:///tmp/google-snapshot.jpg');
  }
  setTimeout(function(){
    phantom.exit();
  },2000);
});

Reference: https://github.com/ariya/phantomjs/pull/14220

Comments