如何使用nodejs打开默认浏览器并导航到特定URL

Qin*_* Xu 118 javascript node.js

我正在使用Node.js编写应用程序.

我想要创建的功能之一是打开默认Web浏览器并导航到特定URL.

我希望它是便携式的,以便它可以在Windows/Mac/Linux上运行.

For*_*say 150

使用opn因为它将处理跨平台问题.安装:

$ npm install opn
Run Code Online (Sandbox Code Playgroud)

使用:

var opn = require('opn');

// opens the url in the default browser 
opn('http://sindresorhus.com');

// specify the app to open in 
opn('http://sindresorhus.com', {app: 'firefox'});
Run Code Online (Sandbox Code Playgroud)

  • 不确定,可能值得尝试https://github.com/domenic/opener作为具有相同API的替代模块。看来它具有适当的问题跟踪工具,可以打开该问题。不过,这可能只是浏览器如何报告进程结束的一种奇怪方式,因此它可能不容易修复。 (2认同)
  • 它看起来像开启者在Mac/Windows/Linux上工作,而open只能在Mac/Windows上工作,所以开放者更可取. (2认同)

lex*_*a-b 28

var url = 'http://localhost';
var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open');
require('child_process').exec(start + ' ' + url);
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是,至少在 Windows 上,URL 中的“&”应该用“^&”转义 (2认同)
  • 我包装了类似的逻辑,承诺它并发布到 npm https://www.npmjs.com/package/out-url (2认同)

Oli*_*r C 10

不推荐使用node-open 。现在使用open

const open = require('open')

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

await open('http://sindresorhus.com', {app: 'firefox'}) // Specify the app to open in
Run Code Online (Sandbox Code Playgroud)


小智 7

安装:

$ npm install open
Run Code Online (Sandbox Code Playgroud)

用法:

const open = require('open');
 
(async () => {
    // Opens the image in the default image viewer and waits for the opened app to quit.
    await open('unicorn.png', {wait: true});
    console.log('The image viewer app quit');
 
    // Opens the URL in the default browser.
    await open('https://sindresorhus.com');
 
    // Opens the URL in a specified browser.
    await open('https://sindresorhus.com', {app: 'firefox'});
 
    // Specify app arguments.
    await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
})();
Run Code Online (Sandbox Code Playgroud)

  • 您好,感谢您分享这个答案。最好添加有关 async/await 的文档链接以供参考。不过代码中的注释很好:) (2认同)

Vad*_*dim 7

Windows + Express

app.listen(3000, ()=>{
    require('child_process').exec('start http://localhost:3000/');
});
Run Code Online (Sandbox Code Playgroud)


Sor*_*ren 6

您可能需要使用 ...

require('os').type()
Run Code Online (Sandbox Code Playgroud)

然后使用spawn("open")spawn("xdg-open")取决于平台?

  • 在 Windows 中,我尝试 spawn("explorer.exe",['http://www.stackoverflow.com']),Windows 资源管理器将选择默认浏览器打开 URL。 (4认同)
  • @QingXu 太棒了!`require('child_process').spawn('explorer', ['url'])` 是一个不错的单行器! (2认同)