Node.js可以调用Chrome吗?

Bil*_*ian 9 google-chrome node.js

在桌面上运行的Node.js是否可以生成Chrome浏览器窗口?我想在Node.js收到活动时启动Chrome浏览器,提供窗口大小和位置.

sys shell命令只是方法吗?

小智 14

在MacOSX上

var childProc = require('child_process');
childProc.exec('open -a "Google Chrome" http://your_url', callback);
//Or could be: childProc.exec('open -a firefox http://your_url', callback);
Run Code Online (Sandbox Code Playgroud)

多一点:


ebi*_*del 9

结帐https://www.npmjs.com/package/chrome-launcher

启动铬:

const chromeLauncher = require('chrome-launcher');

chromeLauncher.launch({
  startingUrl: 'https://google.com'
}).then(chrome => {
  console.log(`Chrome debugging port running on ${chrome.port}`);
});
Run Code Online (Sandbox Code Playgroud)

启动无头镀铬:

const chromeLauncher = require('chrome-launcher');

chromeLauncher.launch({
  startingUrl: 'https://google.com',
  chromeFlags: ['--headless', '--disable-gpu']
}).then(chrome => {
  console.log(`Chrome debugging port running on ${chrome.port}`);
});
Run Code Online (Sandbox Code Playgroud)

chrome-launcher 打开一个远程调试端口,因此您还可以使用DevTools 协议控制浏览器实例。

Puppeteer是另一种启动 Chrome 并使用高级 API 与之交互的方式。


seq*_*ell 5

我在Windows上打开一个新的firefox选项卡:https: //github.com/Sequoia/FTWin/blob/master/FTWin.n.js

最突出的部分:

var cp = require('child_process'),
    url_to_open = 'http://duckduckgo.com/';

cp.spawn('c:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe', ['-new-tab', url_to_open]);
Run Code Online (Sandbox Code Playgroud)

注意:

  1. 将firefox 的完整路径传递给child_process.spawn
  2. 逃避斜线
  3. 将开关/参数传递给firefox.exe:作为数组传递cp.spawn的第二个参数(每个开关一个条目).

此调用相当于"c:\Program Files (x86)\Mozilla Firefox\firefox.exe" -new-tab http://duckduckgo.com在Windows命令行中键入.

对于chrome你想要的东西,D:\Users\sequoia\AppData\Local\Google\Chrome\Application\chrome.exe --new-tab http://duckduckgo.com/ 我会让你自己解决child_process版本;)

参考文献:

http://peter.sh/experiments/chromium-command-line-switches/

http://nodejs.org/docs/v0.3.1/api/child_processes.html


Oli*_*r C 5

使用opn

const opn = require('opn');
opn('http://siteurl.com/', {app: ['google chrome']});
Run Code Online (Sandbox Code Playgroud)

  • opn 已弃用并重新命名为“open” (3认同)

use*_*782 -4

var exec = require('child_process').exec

exec('open firefox www.google.pt' , function(err) {
if(err){ //process error
}

else{ console.log("success open")
}

})
Run Code Online (Sandbox Code Playgroud)

这会从nodejs脚本在google页面中打开firefox,对于chrome来说应该是相同的

  • 在 Windows 上 `exec('启动 chrome www.google.com', function (err) {` (4认同)