Skip to content

Instantly share code, notes, and snippets.

@Senci
Last active February 11, 2016 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Senci/dcdff71e6197b4af1154 to your computer and use it in GitHub Desktop.
Save Senci/dcdff71e6197b4af1154 to your computer and use it in GitHub Desktop.
Holding reference on phantom Object in node context of phridge
/**
* THIS CODE DOES NOT WORK PROPERLY (yet). KEEP THAT IN MIND WHEN TRYING TO USE THIS!
*/
var phridge = require('phridge'); // https://www.npmjs.com/package/phridge
var through = require('through'); // https://www.npmjs.com/package/through
var S = require('string'); // https://www.npmjs.com/package/string
S.extendPrototype();
var Promise = require('promise'); // https://www.npmjs.com/package/promise
phridge.config.stdout = through(function(data){
this.queue(data);
}, function(){
this.queue(null);
});
// setup
phridge.config.stdout.on('data', function(data) {
if (data.startsWith('myMsg:')) {
// clean "myMsg:"
data = data.substr(6);
// clean trailing newline
if (data[data.length-1] == '\n') {
data = data.substr(0, data.length-1);
}
console.log(data);
}
});
var phantomInstances = {};
function spawnPhantom (id) {
return new Promise(function (resolve,reject) {
phridge.spawn().then(function(phantom) {
phantomInstances[id] = phantom; // <- important line, why does this not work properly?
phantom.run(function () {
this.page = webpage.create();
this.page.onCallback = function(data) {
console.log('myMsg:'+data);
};
// this.page.injectJs('simpleLogScript.js'); // if executed here, everything works like a charm.
}).then(function () {
console.log('Phantom instance ('+ id +') successfully spawned.');
resolve();
});
});
});
}
function injectScriptIntoPhantom (phantomId, scriptPath) {
var myPhantom = phantomInstances[phantomId]; // <- important line, why does this not work properly?
myPhantom.run(function() {
this.page.injectJs(scriptPath);
});
}
spawnPhantom('myId0').then(function () {
injectScriptIntoPhantom('myId0', 'simpleLogScript.js'); // leads to rejection.
});
window.callPhantom('Hello World!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment