由于您想从 node.js 执行此操作,因此应该使用 PhantomJS 桥接器,例如phantomjs-节点 (phantomnpm 模块)。
当你不在 PhantomJS 中打开页面时,你实际上是在一个 about:blank 页面中工作,你需要为底层 PhantomJS 进程添加 '--local-to-remote-url-access=yes' 命令行选项,以便可以加载远程资源。或许--web-security=false
, --ssl-protocol=any
and ignore-ssl-errors=true
可能有必要。
要将其他脚本注入 DOM,您需要使用injectJs()对于本地文件和includeJs()对于远程文件。此外,你不能直接访问 PhantomJS 中的 DOM,因为它有两个上下文。沙盒页面上下文 (page.evaluate()) 无法访问外部定义的变量,因此如果需要,您需要将它们显式传入。
var phantom = require('phantom');
var async = require('async');
function run(page, ph) {
page.evaluate(function () {
// page context: DOM code here
return document.title;
}, function (title) {
// node code here
console.log('Page title is ' + title);
ph.exit();
});
}
var remoteScripts = [ "http://d3js.org/d3.v3.min.js" ];
var localScripts = [ "../js/d3.v3.min.js", "../js/jquery-2.1.3.min.js" ];
phantom.create('--local-to-remote-url-access=yes', '--web-security=false', function (ph) {
ph.createPage(function (page) {
async.series(remoteScripts.map(function(url){
return function(next){
page.includeJs(url, function(){
next();
});
};
}), function(){
async.series(localScripts.map(function(url){
return function(next){
page.injectJs(url, function(){
next();
});
};
}), function(){
run(page, ph);
});
});
});
});
您可以使用async将脚本列表加载到 DOM 中。我用的是series()
功能。