无法让page.injectJs()在PhantomJS中工作
我在我的代码中有以下内容:
phantom.createPage(function(page){ page.onCallback = function(data) { console.log("ph callback: ", data); }; page.open(req.query.testUrl, function(status){ if(status !== 'success'){ page.close(); res.status(500) .send('Page "' + testUrl + '" could not be loaded.') .end(); return; } var result = page.injectJs('lib/my-test-script.js'); console.log('injectJS: ', result); page.evaluate(function(){ window.callPhantom(window.mocha.constructor.name); }, function(){ console.log('finished'); page.close(); res.json({status: status}); res.end(); }); }); });
和console.log('injectJS: ', result);
正在输出“injectJS:undefined”,而不是显式false
因为文档在这里说:
http://phantomjs.org/api/webpage/method/inject-js.html
此外,我已经validation了my-test-script.js是使用fs.readDir()
,但是看起来我的代码并没有被注入,更不用说,我从来没有从page.onCallback()
获得控制台输出page.onCallback()
。
我完全失去了这一点。 我显然做错了什么,但是我不知道它会是什么。 任何帮助,将不胜感激。
关联的GitHub问题 。
您正在使用node.js和PhantomJS(可能是phantomjs-node )之间的桥梁,所以PhantomJS文档不能直接应用。
所有的桥接function(基本上所有的PhantomJSfunction)如果还没有这样的话,就会采取额外的callback。 这在桥梁文档中的function细节下进行了描述。 injectJs也是如此。 另外,您注册事件的方式也不同:
page.set("onCallback", function(data) { console.log("ph callback: ", data); }); ... page.injectJs('lib/my-test-script.js', function(){ page.evaluate(function(){ window.callPhantom(window.mocha.constructor.name); }, function(){ console.log('finished'); page.close(); res.json({status: status}); res.end(); }); });