UNPKG

1.55 kBJavaScriptView Raw
1var execSync = require('child_process').execSync;
2var opn = require('opn');
3
4// https://github.com/sindresorhus/opn#app
5var OSX_CHROME = 'google chrome';
6
7function openBrowser(url) {
8 // Attempt to honor this environment variable.
9 // It is specific to the operating system.
10 // See https://github.com/sindresorhus/opn#app for documentation.
11 const browser = process.env.BROWSER;
12
13 // Special case: BROWSER="none" will prevent opening completely.
14 if (browser === 'none') {
15 return false;
16 }
17
18 // If we're on OS X, the user hasn't specifically
19 // requested a different browser, we can try opening
20 // Chrome with AppleScript. This lets us reuse an
21 // existing tab when possible instead of creating a new one.
22 const shouldTryOpenChromeWithAppleScript = (
23 process.platform === 'darwin' && (
24 typeof browser !== 'string' ||
25 browser === OSX_CHROME
26 )
27 );
28
29 if (shouldTryOpenChromeWithAppleScript) {
30 try {
31 // Try our best to reuse existing tab
32 // on OS X Google Chrome with AppleScript
33 execSync('ps cax | grep "Google Chrome"');
34 execSync(
35 'osascript openChrome.applescript ' + url,
36 { cwd: __dirname, stdio: 'ignore' }
37 );
38 return true;
39 } catch (err) {
40 // Ignore errors.
41 }
42 }
43
44 // Fallback to opn
45 // (It will always open new tab)
46 try {
47 var options = { app: browser };
48 opn(url, options).catch(() => { }); // Prevent `unhandledRejection` error.
49 return true;
50 } catch (err) {
51 return false;
52 }
53}
54
55module.exports = openBrowser;