您将如何从node.js命令行脚本启动浏览器

时间:2011-10-05 16:30:54

标签: shell command-line node.js

  

可能重复:
  How to use nodejs to open default browser and navigate to a specific URL

我不知道这是否重要,但我在OSX上。

我知道您可以通过输入以下命令从命令行启动浏览器:

open http://www.stackoverflow.com

但是有没有办法从nodejs命令行脚本中打开浏览器?

1 个答案:

答案 0 :(得分:92)

Open现在存在,请使用它。 :)

安装时:

$ npm install --save open

使用:

const open = require('open');

// Opens the image in the default image viewer
(async () => {
    await open('unicorn.png', {wait: true});
    console.log('The image viewer app closed');

    // Opens the url in the default browser
    await open('https://sindresorhus.com');

    // Specify the app to open in
    await open('https://sindresorhus.com', {app: 'firefox'});

    // Specify app arguments
    await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
})();

app: ...选项:

Type: string | string[]

  

指定用于打开目标的应用程序,或指定带有应用程序的数组   应用参数。

     

应用名称取决于平台。不要在可重用的情况下对其进行硬编码   模块。例如,Chrome是macOS上的谷歌浏览器,谷歌浏览器   在Windows上使用Linux和Chrome。

     

您也可以传递应用的完整路径。例如,在WSL上,这可以   be / mnt / c / Program Files(x86)/Google/Chrome/Application/chrome.exe for   Chrome的Windows安装。

示例:

open('http://localhost', {app: "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"});