我正在尝试使用 spawn
在 Windows 7 上通过 node.js 打开 Google Chrome。它似乎适用于除设置 user-data-dir 之外的所有参数。但是,--user-data-dir
直接从命令行工作,如果我从 Node 调用 .cmd 文件并通过它传递参数,它也可以工作。
Chrome 在后台打开(在任务管理器中显示),但浏览器窗口未打开,我必须在任务管理器中手动终止该进程才能结束它。
我没有收到任何错误或任何问题的指示。
这是我的 Node 代码:
var spawn = require('child_process').spawn;
var exe = 'C:\\Program Files\\Google\\Chrome\\application\\chrome.exe';
//this does not work and gives no errors just starts chrome in the background but fails to open browser window
// var args = [
// '--user-data-dir=C:\\Windows\\Temp\\testingdir',
// 'http://www.google.com'
// ];
//actual output from running this through a .cmd file and echoing out the arguments
// --user-data-dir=C:\Windows\Temp\testingdir http://www.google.com
//running the above arguments through a .cmd file from nodejs or manually running them in the cli works
//this works from nodejs, other arguments work too, just not the --user-data-dir argument
// var args = ['http://www.google.com'];
chrome = spawn(exe, args);
chrome.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
chrome.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
chrome.on('exit', function (code) {
console.log('child process exited with code ' + code);
// chrome.kill();
});
正如您在注释掉的代码中看到的那样,只要我不尝试更改用户数据目录,它就可以工作。我尝试了不同的临时目录,并在临时目录上设置了对“每个人”的完全访问权限,以防出现权限问题。
更新:我刚刚从 v0.8.1 更新到最新的 v0.8.14,现在当它失败时 on('exit', function())
实际上返回一个代码。
child process exited with code 20
如何查找此代码以了解其含义?
更新 2 我认为退出代码 20 只是一次侥幸,因为我无法再重现它。尝试测试不同的东西有点麻烦,因为我必须记住每次都杀死任务管理器中的 chrome 进程,以确保得到相同的结果。所以它又回到了和以前一样的结果,没有错误,但没有 chrome 窗口,并且一些正在运行的 chrome 进程必须手动终止。
更新3 我刚刚将此脚本移至 Ubuntu 并更改了 exe 和 args 以反射(reflect)不同的文件结构,并且它可以在 Ubuntu 上运行。
exe = "/opt/google/chrome/google-chrome"
和
args = [
"http://www.google.com",
"--user-data-dir=/home/lotus/testdir"
];
所以我可以确认这与 Windows 上的 Chrome 特别相关。
最佳答案
关于windows - node.js,Windows 7,spawn chrome,无法设置用户数据目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13211706/