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

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.

Answers:

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

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
Answer

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?

Answer

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:[email protected]")

Answer

Use opn because it will handle the cross platform issue. To install:

$ npm install opn

To use:

var opn = require('opn');

// opens the url in the default browser 
opn('http://sindresorhus.com');

// specify the app to open in 
opn('http://sindresorhus.com', {app: 'firefox'});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.