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

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

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

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

148145 次浏览

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

require('os').type()

然后根据平台使用 spawn("open")spawn("xdg-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'});

最简单和最简洁的方法是使用名为 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")

Node-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
var url = 'http://localhost';
var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open');
require('child_process').exec(start + ' ' + url);

安装:

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

Windows + Express

app.listen(3000, ()=>{
require('child_process').exec('start http://localhost:3000/');
});
#!/usr/bin/env node


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