diff --git a/README.md b/README.md index cfb8cf6..ef23a24 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,16 @@ const opn = require('better-opn'); opn('http://localhost:3000'); ``` +### Reuse tab by match host + +In case your app can navigate to another pathnames and still want to reuse opened tab, set environment variable `OPEN_MATCH_HOST_ONLY=true` can tell this program to find reusable tab by only match the host part of your URL. + +```js +process.env.OPEN_MATCH_HOST_ONLY = 'true'; + +opn('http://localhost:3000/foo/bar'); // This will reuse any tab with URL starting with http://localhost:3000/ +``` + ## Author - [Michael Lin](https://michaellin.me) diff --git a/openChrome.applescript b/openChrome.applescript index c6c9c66..b7b0161 100644 --- a/openChrome.applescript +++ b/openChrome.applescript @@ -90,4 +90,4 @@ on lookupTabWithUrl(lookupUrl) end tell end using terms from return found -end lookupTabWithUrl \ No newline at end of file +end lookupTabWithUrl diff --git a/src/index.js b/src/index.js index 3893288..575d178 100644 --- a/src/index.js +++ b/src/index.js @@ -28,6 +28,20 @@ const getBrowserEnv = () => { return {action, value, args}; }; +const normalizeURLToMatch = target => { + // We may encounter URL parse error but want to fallback to default behavior + try { + // Url module is deprecated on newer version of NodeJS, only use it when URL class is not supported (like Node 8) + const URL = + // eslint-disable-next-line node/prefer-global/url + typeof global.URL === 'undefined' ? require('url').URL : global.URL; + const url = new URL(target); + return url.origin; + } catch { + return target; + } +}; + // Copy from // https://github.com/facebook/create-react-app/blob/master/packages/react-dev-utils/openBrowser.js#L64 // eslint-disable-next-line unicorn/prevent-abbreviations @@ -57,7 +71,9 @@ const startBrowserProcess = (browser, url, opts = {}, args = []) => { execSync('ps cax | grep "' + chromiumBrowser + '"'); execSync( `osascript ../openChrome.applescript "${encodeURI( - url + process.env.OPEN_MATCH_HOST_ONLY === 'true' + ? normalizeURLToMatch(url) + : url )}" "${chromiumBrowser}"`, { cwd: __dirname, diff --git a/test/host-only.js b/test/host-only.js new file mode 100644 index 0000000..894722f --- /dev/null +++ b/test/host-only.js @@ -0,0 +1,5 @@ +const opn = require('../dist/index'); + +// Run test/open.js first, then run this to ensure tab is reused +process.env.OPEN_MATCH_HOST_ONLY = 'true'; +opn('http://localhost:8000/foo/bar');