Javascript 如何使用 nodejs 打开默认浏览器并导航到特定 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8500326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use nodejs to open default browser and navigate to a specific URL
提问by Qing Xu
I'm writing an application using Node.js.
我正在使用 Node.js 编写应用程序。
One of the functions I want to create is to open the default web browser and navigate to a specific URL.
我想要创建的功能之一是打开默认的 Web 浏览器并导航到特定的 URL。
I want it to be portable so that it runs on Windows/Mac/Linux.
我希望它是可移植的,以便它可以在 Windows/Mac/Linux 上运行。
回答by ForbesLindesay
回答by lexa-b
var url = 'http://localhost';
var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open');
require('child_process').exec(start + ' ' + url);
回答by Olivier C
node-open is deprecated. Now use 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
回答by Soren
You may need to implement a switch using the value of ...
您可能需要使用 ...
require('os').type()
And then use spawn("open")
or spawn("xdg-open")
depending on the platform?
然后使用spawn("open")
或spawn("xdg-open")
取决于平台?
回答by EL Taipan
The easiest and neatest way, IMHO is using an npm package called openurl. Do a npm install openurl
. You could try this real quick in your Nodejs REPL
恕我直言,最简单和最简洁的方法是使用一个名为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("http://stackoverflow.com/questions/8500326/how-to-use-nodejs-to-open-default-browser-and-navigate-to-a-specific-url")
You could also send emails with it if the need arises like so;
require("openurl").open("mailto:[email protected]")
如果需要,你也可以用它发送电子邮件;
require("openurl").open("mailto:[email protected]")