Last active
February 11, 2016 17:19
-
-
Save Senci/dcdff71e6197b4af1154 to your computer and use it in GitHub Desktop.
Holding reference on phantom Object in node context of phridge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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. | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.callPhantom('Hello World!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment