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

203

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

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

我希望它是可移植的,可以在Windows/Mac/Linux上运行。


3
我猜这个问题是你正在寻找的:https://dev59.com/vmsz5IYBdhLWcg3wxq4V - TomTasche
是的,它在Mac上可以运行。它能在Windows和Linux上运行吗?我手头没有Windows机器。 - Qing Xu
1
xdg-open 在 Linux 上正常工作 :) - Qing Xu
10个回答

258

使用 open(以前称为 opn)因为它可以解决跨平台问题。安装方式如下:

$ npm install open

使用方法:

const open = require('open');

// opens the url in the default browser 
open('http://sindresorhus.com');
 
// specify the app to open in 
open('http://sindresorhus.com', {app: 'firefox'});

1
ForbesLindesay回调函数立即被调用,而不是在窗口关闭时才调用。有什么想法吗? - Sam Selikoff
3
不确定,或许值得尝试一下 https://github.com/domenic/opener 作为同样具备API的替代模块。它似乎有一个合适的问题跟踪器,你可以在上面提交一个问题。这可能只是浏览器报告进程结束方式的怪异现象,因此可能不容易修复。 - ForbesLindesay
2
看起来opener在Mac / Windows / Linux上都可以工作,而open仅在Mac / Windows上工作,因此opener更可取。 - Tom
这对我有用,但似乎子进程没有分离,所以当服务器关闭时,我的 Firefox 也会关闭!不确定如何让 "open" 分离子进程... 有什么想法吗? - sidewinderguy
问题在于,当我使用nodemon并自动刷新更改时,opn()会打开另一个窗口。因此,每次保存时,浏览器中都会打开新窗口。 - Marko
显示剩余5条评论

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

5
需要注意的是,在Windows系统中,URL中的&符号需要用^&进行转义。 - junvar
2
我将类似的逻辑进行了封装,将其转换为 Promise,并发布到了 npm 上。 https://www.npmjs.com/package/out-url - azhar22k
1
谢谢 ❤️ 尽量少依赖第三方库 = 更好 - Endless
真的很有效。在我们不需要安装依赖项的遗留代码中运行得更好。 - realsajeel289

12

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

7

安装:

$ npm install open

使用方法:

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']});
})();

2
你好,感谢分享这个答案。为了参考,可以添加一个关于async/await文档的链接。不过代码中的注释很好 :) - William Patton

6

Windows + Express

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

6
您可能需要使用枚举值实现开关...
require('os').type()

然后根据平台使用 spawn("open") 或者 spawn("xdg-open") 来执行操作?


4
在Windows系统中,我尝试使用spawn("explorer.exe",['http://www.stackoverflow.com'])命令,Windows资源管理器将选择默认浏览器来打开该URL。 - Qing Xu
2
@QingXu 很棒!require('child_process').spawn('explorer', ['url']) 这个一行命令真不错! - TWiStErRob

3

简单使用

require('child_process').exec('start https://www.google.co.in/');

这对我有用。


2

在我看来,最简单和最整洁的方法是使用一个名为openurl的npm包。执行npm install openurl即可。你可以在Nodejs REPL中快速尝试一下。

require("openurl").open("https://dev59.com/t2oy5IYBdhLWcg3wguWS")

如果需要,你也可以使用它发送电子邮件,像这样;require("openurl").open("mailto:janedoe@example.com")


1
#!/usr/bin/env node

const url = 'http://localhost'
require('child_process')
  .exec((process.platform
         .replace('darwin','')
         .replace(/win32|linux/,'xdg-') + 'open ' + url));

1
请考虑添加一个简短的解释,说明如何以及为什么这个解决方案能够解决问题。这将有助于读者更好地理解您的解决方案。 - tdy
在SO上,仅提供代码的答案通常会被反对并且经常会被踩。为了理解给定的解决方案并区分何时应该/不应该应用您的解决方案,通常需要上下文和解释。带有解释的答案对于未来的访问者更有帮助,因此更容易得到赞同。SO旨在成为一个学习如何解决问题的地方。同时,指出特定答案适用的上下文(例如操作系统平台或特定边缘情况)也是很好的。鼓励提供文档或进一步信息的链接(但实际解决方案也必须嵌入其中)。 - SherylHohman

0
var url = '\\index.html';
var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open');
require('child_process').exec(start + ' ' + __dirname + url);

Lexa-B 的回答对我最有效,但是我遇到了“Windows 无法找到 index.html”错误。我正在使用 Lexa-B 的代码 child_process exec 命令来打开我正在编写的 npm 包中的本地网页。当我使用 npx 命令在 package bin.js 中运行它/打开它时,需要打开一个 html 文件。

需要做的只是将 __dirname 追加到文件路径中,以确保相对目录路径正确,用于调用 child_process 的文件。child_process 运行在主文件夹中,远离 npx 临时文件位置。__dirname 解决了这个问题并连接了两者,解决了我的文件缺失错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接