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

10

210

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.

Ensor answered 14/12, 2011 at 6:29 Comment(3)
I guess this question is what you're looking for: #7665105Reg
yep, it works in Mac. does it work in Windows and Linux? i didn't have a window machine in handEnsor
xdg-open is working in Linux :)Ensor
A
261

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'});
Annamarieannamese answered 16/11, 2012 at 15:32 Comment(10)
ForbesLindesay the callback is being called immediately, instead of when the window is closed. Any ideas?Stationer
Not sure, might be worth giving github.com/domenic/opener a try as an alternative module with the same API. It looks like it has a proper issue tracker you could open an issue on. It may just be an oddity of how browsers report the process as ending though, so it may not be easily fixable.Annamarieannamese
It looks like opener works on Mac / Windows / Linux whereas open only works on Mac / Windows so opener is preferable.Gaea
This works for me, but it appears the child process is not detached, so when the server goes down, so does my firefox! Not sure how to get "open" to detach the child process... any idea?Cerise
To answer my own question (maybe) it looks like the "opener" package has an "unref()" call that lets you detach. So maybe that's another reason to use "opener" instead of "open" package. Not sure though.Cerise
Well, I tried "opener" with "unref()" and it doesn't work for me (on linux). Not sure what to do. Seems like everyone would want the browser process to stay open, even if node dies, right?Cerise
Well, the problem with this is that when I use nodemon and changes get automatically refreshed, opn() opens another window. So every time you save, new window in browser opens up.Eddra
Now how do I get data back from this browser, for example as part of an SSO flow?Clem
@AjaxLeung you'd usually do this via some other channel. e.g. for SSO you can generate a secure random token, include it in the OAuth request, and have a server store the auth result along with that token, then your CLI can use that token to request the result.Annamarieannamese
FWIW, open seems to support Linux now.Bergama
I
98
var url = 'http://localhost';
var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open');
require('child_process').exec(start + ' ' + url);
Incubus answered 27/2, 2018 at 16:23 Comment(4)
Should be noted, on windows at least, &'s in the URL should be escaped with ^&Chamade
I wrapped similar logic, promisified it and published to npm npmjs.com/package/out-urlBoigie
Thank you ❤️ less / native dependency free = betterStarstarboard
It really worked. Works better with legacy code where we don't have to install dependencies.Dyun
S
12

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
Suksukarno answered 17/1, 2017 at 3:22 Comment(0)
U
8

Windows + Express

app.listen(3000, ()=>{
    require('child_process').exec('start http://localhost:3000/');
});
Unbreathed answered 31/8, 2021 at 17:4 Comment(0)
H
7

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']});
})();
Howie answered 24/11, 2020 at 21:1 Comment(1)
Hi there, thank you for sharing this answer. A link to the documentation on async/await would be nice to add just for reference. Nice comments in the code though :)Secondbest
C
6

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?

Contumelious answered 14/12, 2011 at 7:37 Comment(2)
In windows, i try spawn("explorer.exe",['stackoverflow.com']), the windows explorer will select the default browser to open the URL.Ensor
@QingXu awesome! require('child_process').spawn('explorer', ['url']) is a nice oneliner!Drake
T
4

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("https://mcmap.net/q/126228/-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]")

Ti answered 24/9, 2016 at 22:25 Comment(0)
C
4

Simply Use

require('child_process').exec('start https://www.google.co.in/');

It's Worked For me.

Courcy answered 18/4, 2023 at 7:38 Comment(0)
S
1
#!/usr/bin/env node

const url = 'http://localhost'
require('child_process')
  .exec((process.platform
         .replace('darwin','')
         .replace(/win32|linux/,'xdg-') + 'open ' + url));
Stria answered 23/11, 2021 at 15:17 Comment(2)
Please consider adding a brief explanation of how and why this solves the problem. This will help readers to better understand your solution.Yarrow
Code only answers are frowned upon on SO and are often downvoted. Context and explanation are usually necessary for understanding the given solution, and to distinguish when your solution should/should not be applied. Answers with explanations are more helpful to future visitors, thus upvoted much more often. SO is designed to be a place to learn how to fix issues. It is also good to indicate the context for which a particular answer applies, such as OS platform, or specific edge cases. Links to documentation or further info are also encouraged (but the actual solution must also be embeded.)Tuberose
W
0
var url = '\\index.html';
var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open');
require('child_process').exec(start + ' ' + __dirname + url);

Lexa-B’s answer worked best for me, but I was getting “Windows could not locate index.html” error. I was using lexa-b code child_process exec command to open a local webpage within an npm package I was writing. Needed to open an html file in my npm package when running it / opening it from package bin.js with npx command.

All that was needed was to append __dirname to file path to ensure the relative directory path to the file calling the child_process was correct. The child_process was running at the home folder, which is far away from the npx temp file location. __dirname solves that problem and links the two, solving my missing file error.

Weir answered 18/6, 2023 at 6:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.