开发者

How would you launch a browser from the a node.js command line script [duplicate]

This question already has answers here: How to use nodejs to open default browser and navigate to a specific URL (8 answers) 开发者_C百科 Closed 3 months ago.

I don't know if it matters, but I am on OSX.

I know you can launch a browser from the command line itself by typing:

open http://www.stackoverflow.com

But is there a way to open a browser from inside a nodejs command line script?


Open exists now, use that. :)

Install with:

$ npm install --save open

Use with:

const open = require('open');

// Opens the image in the default image viewer
(async () => {
    await open('unicorn.png', {wait: true});
    console.log('The image viewer app closed');

    // Opens the url in the default browser
    await open('https://sindresorhus.com');

    // Specify the app to open in
    await open('https://sindresorhus.com', {app: 'firefox'});

    // Specify app arguments
    await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
})();

The app: ... option:

Type: string | string[]

Specify the app to open the target with, or an array with the app and app arguments.

The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is google chrome on macOS, google-chrome on Linux and chrome on Windows.

You may also pass in the app's full path. For example on WSL, this can be /mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe for the Windows installation of Chrome.

Example:

open('http://localhost', {app: "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"});

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜