Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

node-open is deprecated. Now use 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

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?


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