Dup Goto 📝

GoogleChrome

PT2/macos/applescript 04-30 16:05:38
To Pop
95 lines, 329 words, 2807 chars Thursday 2026-04-30 16:05:38

Get All Tab Urls

From this Gemini query (except tweaking the {ndigs} bit in the output to enumerate rather than use an icon).

A python script for macos using applescript to get all chrome urls.

Could you add main and argparse, and options -b or --bare for bare output (just list the urls), and -j or --json to output the urls as a json array

#!/usr/bin/env python3

import subprocess
import argparse
import json
import sys

def get_chrome_urls():
    """Executes AppleScript to fetch all open URLs from Google Chrome."""
    script = '''
    set urlList to {}
    tell application "Google Chrome"
        if it is running then
            set windowList to every window
            repeat with theWindow in windowList
                set tabList to every tab of theWindow
                repeat with theTab in tabList
                    set end of urlList to URL of theTab
                end repeat
            end repeat
        end if
    end tell
    return urlList
    '''

    try:
        result = subprocess.run(
            ['osascript', '-e', script],
            capture_output=True,
            text=True,
            check=True
        )

        # AppleScript returns an empty string or comma-separated values
        raw_output = result.stdout.strip()
        if not raw_output:
            return []

        # Split by comma and space, then clean up any potential whitespace
        return [url.strip() for url in raw_output.split(',')]

    except subprocess.CalledProcessError:
        return []

def main():
    parser = argparse.ArgumentParser(description="Extract all open URLs from Google Chrome on macOS.")

    # Define mutually exclusive group so you can't try to do bare and json at once
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-b", "--bare", action="store_true", help="Print just the URLs, one per line.")
    group.add_argument("-j", "--json", action="store_true", help="Output URLs as a JSON array.")

    args = parser.parse_args()
    urls = get_chrome_urls()

    if not urls:
        if args.json:
            print("[]")
        else:
            print("No URLs found or Chrome is not running.", file=sys.stderr)
        return

    if args.json:
        print(json.dumps(urls, indent=4))
    elif args.bare:
        for url in urls:
            print(url)
    else:
        # Default "pretty" output
        print(f"--- Found {len(urls)} URLs ---")
        ndigs = len(str(len(urls)))
        for i,url in enumerate(urls,1):
            print(f"{i:>{ndigs}}. {url}")

if __name__ == "__main__":
    main()