I'm writing an application using Node.js.
One of the functions I want to create is to open the default web browser and navigate to a specific URL.
I want it to be portable so that it runs on Windows/Mac/Linux.
Join Stack Overflow to learn, share knowledge, and build your career.
I'm writing an application using Node.js.
One of the functions I want to create is to open the default web browser and navigate to a specific URL.
I want it to be portable so that it runs on Windows/Mac/Linux.
Use open (formerly known as opn
) because it will handle the cross platform issue. To install:
$ npm install open
To use:
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);
&
's in the URL should be escaped with ^&
– junvar
Aug 21 '19 at 13:54
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
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?
require('child_process').spawn('explorer', ['url'])
is a nice oneliner!
– TWiStErRob
Feb 21 '16 at 23:46
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
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:janedoe@example.com")
Install:
$ npm install open
Usage:
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']});
})();