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


135

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

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

我希望它具有可移植性,以便它可以在Windows / Mac / Linux上运行。


3
我想这个问题是你在找什么:stackoverflow.com/questions/7664605/...
TomTasche

是的,它适用于Mac。在Windows和Linux中可以使用吗?我没有手摇窗户的机器
Qing Xu

1
xdg-open在Linux中工作:)
Qing Xu

Answers:


167

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

$ npm install opn

使用方法:

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

ForbesLindesay回调将立即被调用,而不是在关闭窗口时被调用。有任何想法吗?
Sam Selikoff 2014年

2
不确定,可能值得尝试github.com/domenic/opener作为具有相同API的替代模块。看来它具有适当的问题跟踪工具,可以打开该问题。不过,这可能只是浏览器如何报告该过程已结束的一个奇怪现象,因此它可能不容易修复。
ForbesLindesay 2014年

1
这是一个很好的建议,对于OP描述的用例非常有效。
jbranchaud 2014年

2
看起来opener在Mac / Windows / Linux上有效,而open仅在Mac / Windows上有效,因此opener更可取。
汤姆(Tom)

2
请更新以提出建议,opn而不是open现在不建议使用后者。
萨米尔·阿吉亚尔

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

1
应该指出的是,至少在Windows上,&URL中的应当使用^&
junvar '19

1
我包装了类似的逻辑,将其承诺化并发布到npm npmjs.com/package/out-url
azhar22k

6

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

const opn = require('opn')

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

//opn('http://sindresorhus.com', {app: 'firefox'}) // Specify the app to open in

3

您可能需要使用...的值实现开关

require('os').type()

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


4
在Windows中,我尝试使用spawn(“ explorer.exe”,[' stackoverflow.com']),Windows资源管理器将选择默认浏览器以打开URL。
Qing Xu

@PaulIrish:不幸的是,您的链接现在已消失。
mklement0

2
@QingXu太棒了!require('child_process').spawn('explorer', ['url'])是一个很好的单人!
TWiStErRob '16

2

恕我直言,最简单,最整洁的方法是使用一个名为openurl的npm包。做一个npm install openurl。您可以在Nodejs REPL中快速尝试这种方法

require("openurl").open("http://stackoverflow.com/questions/8500326/how-to-use-nodejs-to-open-default-browser-and-navigate-to-a-specific-url")

如果需要,您也可以发送电子邮件; require("openurl").open("mailto:janedoe@example.com")

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.