Implementing Chrome's --focus Flag

โšก Chromium ๐Ÿ”ง C++ ๐Ÿ‘ค Helmut Januschka

A command-line option for focusing an existing tab instead of opening a duplicate.

Update 16.10.2025: โœ… Feature landed in Chromium main branch (Chrome 143)

The Initial Request

A tweet from @tobi proposed a command-line option for a common automation problem: focus an existing matching tab instead of opening another copy.

His proposed CLI syntax was clean:

chrome --focus=https://github.com/user/repo

From Request to Implementation

The expected behavior was:

Technical Design

Turning Behavior into Architecture

The spec translated into several technical challenges:

  1. Selector Parsing: Supporting exact URLs, wildcards, and app IDs
  2. MRU Logic: Finding and focusing the most recently used tab
  3. Cross-Window Search: Looking across all Chrome windows
  4. Result Reporting: JSON output for automation scripts

The Implementation

The implementation follows Chrome's architecture patterns:

// Parse the selector syntax
std::vector<Selector> ParseSelectors(const std::string& input);

// Find matches across all windows
std::vector<MatchCandidate> CollectMatchingTabs(
    const Selector& selector,
    const std::vector<Browser*>& browsers);

// MRU selection - the heart of the feature
void SortCandidatesByMRU(std::vector<MatchCandidate>& candidates);

Making MRU Work

The less direct requirement was "pick the most recently used." The implementation uses session ordering as a practical recency proxy:

// Leverage Chrome's SessionID ordering as a proxy for recency
bool CompareMRU(const MatchCandidate& a, const MatchCandidate& b) {
  return a.tab->session_id() > b.tab->session_id();
}

SessionIDs increase monotonically, so higher IDs = more recently created. Not perfect MRU, but a pragmatic solution that works.

The Result

The feature now supports:

Basic Usage

# Focus a specific URL
chrome --focus="https://github.com/chromium/chromium"

# Wildcard matching
chrome --focus="*github.com/chromium/*"

# Multiple selectors (first match wins)
chrome --focus="*github.com/*,*gitlab.com/*"

Advanced Features

# JSON output for scripting
chrome --focus="*github.com/*" --output-json

# Open if not found
chrome --focus="https://example.com" --allow-create

# App ID matching
chrome --focus="app-id:abcdefghijklmnop"

Use Cases

The option can be used for:

  1. Shell integration: Bind keys to focus specific tabs
  2. IDE integration: Open documentation without creating duplicate tabs
  3. Workflow automation: Let scripts select browser content and read a JSON result
  4. Tab management: Reuse an existing match when one is available

Acknowledgments

Thanks to:

Implementation Details

Status: โœ… All CLs merged to Chromium main branch


Links: