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

jw5wzhpr  于 2023-04-19  发布在  Java
关注(0)|答案(9)|浏览(208)

我正在使用Node.js编写应用程序。
我想创建的功能之一是打开默认的Web浏览器并导航到特定的URL。
我希望它是便携式的,以便它在Windows/Mac/Linux上运行。

qaxu7uf2

qaxu7uf21#

使用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'});
3qpi33ja

3qpi33ja2#

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

o2g1uqev3#

node-open是deprecated。现在使用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
fnvucqvd

fnvucqvd4#

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

require('os').type()

然后根据平台使用spawn("open")spawn("xdg-open")

hec6srdp

hec6srdp5#

安装:

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

qoefvg9y6#

Windows + Express

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

gdx19jrr7#

最简单和最整洁的方法,恕我直言,是使用名为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")

yduiuuwa

yduiuuwa8#

#!/usr/bin/env node

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

nkoocmlb9#

简单使用

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

对我很有效。

相关问题