繁体   English   中英

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

[英]How to use nodejs to open default browser and navigate to a specific URL

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

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

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

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

不推荐使用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

您可能需要使用 ...

require('os').type()

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

安装:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM