How to focus an already open browser tab (Chromium and macOS)
- Published at
- Updated at
- Reading time
- 3min
While reading an article about "unknown" Netlify CLI features, I discovered a little developer experience gem.
When you run netlify dev
, netlify will check if there’s an open browser tab on the existing port and if so, it’ll re use that tab to display your project as opposed to spinning up a new tab every time.
As a tab hoarder, I appreciate it when development tools reuse and focus already open localhost
tabs. Unfortunately, I can't remember that I've ever seen a development CLI command reusing/focusing an already open tab.
How does that work? Is there an easy way to do that programmatically? And why did I never notice this?
I analyzed what the Netlify CLI does and discovered that it uses the better-opn
npm package (find the usage here). The code to open or focus an already open browser tab is two lines of code.
const open = require('better-opn');
await open('https://example.com);
It can't be that easy! There has to be some magic. Let's dive deeper!
better-opn
has 25 GitHub stars but an astonishing 2 million weekly downloads on npm. I'm always amazed when I discover highly used packages that don't receive GitHub love.
When you look at the package's main file (index
) you'll find out that the "focus existing tab" functionality was initially developed in Facebook's create-react-app
.
// Copy from
// https://github.com/facebook/create-react-app/blob/master/packages/react-dev-utils/openBrowser.js#L64
Looking at the source code; three things stand out:
- focusing a browser tab only works on macOS
- focusing a browser tab only works for Chromium browsers
- focusing a browser tab is not straightforward
The package uses an Apple Script (ufff!) to iterate over open tabs, find the correct URL and focus the appropriate tab.
That's an unfortunate discovery, and here comes the conclusion: I've never noticed this functionality because I use Firefox as my default browser. It never worked for me. 😢
After having another look, better-opn
indeed points out that it only works on Chromium on macOS. My bad, I missed that when scanning the package.
Reuse the same tab on Chromium-based browsers on macOS.
But the Netlify article is not entirely correct then. It only describes the web developer's default stack: Chrome on macOS.
This wording is not a big deal, but it's somewhat concerning that there's no mention of Windows or other browsers.
Not all developers sit in front of a shiny MacBook Pro or use a Chromium-based browser. This case is a typical "Works on my machine" situation. On the other hand, there are no open issues asking for Windows or Firefox support in the better-opn
repo.
Is it just me developing on an exotic software stack? I doubt it, but a solid developer experience should cover more areas than the current developer default stack. 😊
Join 5.5k readers and learn something new every week with Web Weekly.