Skip to content

Commit

Permalink
refactor: update open browser script (#290)
Browse files Browse the repository at this point in the history
  • Loading branch information
exreplay committed Nov 14, 2020
1 parent 74c8aab commit 874a843
Show file tree
Hide file tree
Showing 2 changed files with 119 additions and 81 deletions.
83 changes: 55 additions & 28 deletions packages/@averjs/shared-utils/lib/openBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ import { execSync } from 'child_process';
import spawn from 'cross-spawn';
import open from 'open';

enum Browser {
OSX_CHROME = 'google chrome'
}
// https://github.com/sindresorhus/open#app
const OSX_CHROME = 'google chrome';

const Actions = Object.freeze({
NONE: 0,
Expand All @@ -25,8 +24,11 @@ const Actions = Object.freeze({
function getBrowserEnv() {
// Attempt to honor this environment variable.
// It is specific to the operating system.
// See https://github.com/sindresorhus/opn#app for documentation.
// See https://github.com/sindresorhus/open#app for documentation.
const value = process.env.BROWSER;
const args = process.env.BROWSER_ARGS
? process.env.BROWSER_ARGS.split(' ')
: [];
let action;
if (!value) {
// Default.
Expand All @@ -38,15 +40,15 @@ function getBrowserEnv() {
} else {
action = Actions.BROWSER;
}
return { action, value };
return { action, value, args };
}

function executeNodeScript(scriptPath: string, url: string) {
function executeNodeScript(scriptPath: string | undefined, url: string) {
const extraArgs = process.argv.slice(2);
const child = spawn('node', [scriptPath, ...extraArgs, url], {
const child = spawn(process.execPath, [scriptPath || '', ...extraArgs, url], {
stdio: 'inherit'
});
child.on('close', (code: number) => {
child.on('close', code => {
if (code !== 0) {
console.log();
console.log(
Expand All @@ -61,27 +63,46 @@ function executeNodeScript(scriptPath: string, url: string) {
return true;
}

function startBrowserProcess(browser: string | undefined, url: string) {
function startBrowserProcess(browser: string | string[] | undefined, url: string, args: string[]) {
// If we're on OS X, the user hasn't specifically
// requested a different browser, we can try opening
// Chrome with AppleScript. This lets us reuse an
// existing tab when possible instead of creating a new one.
const shouldTryOpenChromeWithAppleScript =
const shouldTryOpenChromiumWithAppleScript =
process.platform === 'darwin' &&
(typeof browser !== 'string' || browser === Browser.OSX_CHROME);
(typeof browser !== 'string' || browser === OSX_CHROME);

if (shouldTryOpenChromiumWithAppleScript) {
// Will use the first open browser found from list
const supportedChromiumBrowsers = [
'Google Chrome Canary',
'Google Chrome',
'Microsoft Edge',
'Brave Browser',
'Vivaldi',
'Chromium'
];

if (shouldTryOpenChromeWithAppleScript) {
try {
// Try our best to reuse existing tab
// on OS X Google Chrome with AppleScript
execSync('ps cax | grep "Google Chrome"');
execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
cwd: __dirname,
stdio: 'ignore'
});
return true;
} catch {
// Ignore errors.
for (const chromiumBrowser of supportedChromiumBrowsers) {
try {
// Try our best to reuse existing tab
// on OSX Chromium-based browser with AppleScript
execSync('ps cax | grep "' + chromiumBrowser + '"');
execSync(
'osascript openChrome.applescript "' +
encodeURI(url) +
'" "' +
chromiumBrowser +
'"',
{
cwd: __dirname,
stdio: 'ignore'
}
);
return true;
} catch {
// Ignore errors.
}
}
}

Expand All @@ -93,11 +114,17 @@ function startBrowserProcess(browser: string | undefined, url: string) {
browser = undefined;
}

// If there are arguments, they must be passed as array with the browser
if (typeof browser === 'string' && args.length > 0) {
browser = [browser].concat(args);
}

// Fallback to open
// (It will always open new tab)
try {
const options = { app: browser, wait: false };
open(url, options).catch(); // Prevent `unhandledRejection` error.
const options = { app: browser, wait: false, url: true };
// eslint-disable-next-line @typescript-eslint/no-empty-function
open(url, options).catch(() => {}); // Prevent `unhandledRejection` error.
return true;
} catch {
return false;
Expand All @@ -109,15 +136,15 @@ function startBrowserProcess(browser: string | undefined, url: string) {
* true if it opened a browser or ran a node.js script, otherwise false.
*/
function openBrowser(url: string) {
const { action, value } = getBrowserEnv();
const { action, value, args } = getBrowserEnv();
switch (action) {
case Actions.NONE:
// Special case: BROWSER="none" will prevent opening completely.
return false;
case Actions.SCRIPT:
return executeNodeScript(value || '', url);
return executeNodeScript(value, url);
case Actions.BROWSER:
return startBrowserProcess(value, url);
return startBrowserProcess(value, url, args);
default:
throw new Error('Not implemented.');
}
Expand Down
117 changes: 64 additions & 53 deletions packages/@averjs/shared-utils/lib/openChrome.applescript
Original file line number Diff line number Diff line change
Expand Up @@ -7,76 +7,87 @@ LICENSE file at https://github.com/facebook/create-react-app/blob/master/LICENSE
property targetTab: null
property targetTabIndex: -1
property targetWindow: null
property theProgram: "Google Chrome"

on run argv
set theURL to item 1 of argv

tell application "Chrome"
-- Allow requested program to be optional,
-- default to Google Chrome
if (count of argv) > 1 then
set theProgram to item 2 of argv
end if

if (count every window) = 0 then
make new window
end if
using terms from application "Google Chrome"
tell application theProgram

-- 1: Looking for tab running debugger
-- then, Reload debugging tab if found
-- then return
set found to my lookupTabWithUrl(theURL)
if found then
set targetWindow's active tab index to targetTabIndex
tell targetTab to reload
tell targetWindow to activate
set index of targetWindow to 1
return
end if
if (count every window) = 0 then
make new window
end if

-- 1: Looking for tab running debugger
-- then, Reload debugging tab if found
-- then return
set found to my lookupTabWithUrl(theURL)
if found then
set targetWindow's active tab index to targetTabIndex
tell targetTab to reload
tell targetWindow to activate
set index of targetWindow to 1
return
end if

-- 2: Looking for Empty tab
-- In case debugging tab was not found
-- We try to find an empty tab instead
set found to my lookupTabWithUrl("chrome://newtab/")
if found then
set targetWindow's active tab index to targetTabIndex
set URL of targetTab to theURL
tell targetWindow to activate
return
end if
-- 2: Looking for Empty tab
-- In case debugging tab was not found
-- We try to find an empty tab instead
set found to my lookupTabWithUrl("chrome://newtab/")
if found then
set targetWindow's active tab index to targetTabIndex
set URL of targetTab to theURL
tell targetWindow to activate
return
end if

-- 3: Create new tab
-- both debugging and empty tab were not found
-- make a new tab with url
tell window 1
activate
make new tab with properties {URL:theURL}
-- 3: Create new tab
-- both debugging and empty tab were not found
-- make a new tab with url
tell window 1
activate
make new tab with properties {URL:theURL}
end tell
end tell
end tell
end using terms from
end run

-- Function:
-- Lookup tab with given url
-- if found, store tab, index, and window in properties
-- (properties were declared on top of file)
on lookupTabWithUrl(lookupUrl)
tell application "Chrome"
-- Find a tab with the given url
set found to false
set theTabIndex to -1
repeat with theWindow in every window
set theTabIndex to 0
repeat with theTab in every tab of theWindow
set theTabIndex to theTabIndex + 1
if (theTab's URL as string) contains lookupUrl then
-- assign tab, tab index, and window to properties
set targetTab to theTab
set targetTabIndex to theTabIndex
set targetWindow to theWindow
set found to true
using terms from application "Google Chrome"
tell application theProgram
-- Find a tab with the given url
set found to false
set theTabIndex to -1
repeat with theWindow in every window
set theTabIndex to 0
repeat with theTab in every tab of theWindow
set theTabIndex to theTabIndex + 1
if (theTab's URL as string) contains lookupUrl then
-- assign tab, tab index, and window to properties
set targetTab to theTab
set targetTabIndex to theTabIndex
set targetWindow to theWindow
set found to true
exit repeat
end if
end repeat

if found then
exit repeat
end if
end repeat

if found then
exit repeat
end if
end repeat
end tell
end tell
end using terms from
return found
end lookupTabWithUrl
end lookupTabWithUrl

0 comments on commit 874a843

Please sign in to comment.