"""macOS: read the frontmost browser tab URL via AppleScript. Reads local browser state only (no network call to the target site). Requires the terminal/app running this to have Automation permission for the browser. """ import subprocess from typing import Optional # Browsers that expose `URL of active tab of front window` (Chromium family) # or `URL of front document` (Safari). _CHROMIUM = ["Google Chrome", "Brave Browser", "Microsoft Edge", "Arc", "Vivaldi", "Chromium"] def _frontmost_app() -> Optional[str]: script = 'tell application "System Events" to get name of first process whose frontmost is true' return _osascript(script) def _osascript(script: str) -> Optional[str]: try: out = subprocess.run( ["osascript", "-e", script], capture_output=True, text=True, timeout=5, ) val = out.stdout.strip() return val or None except Exception: return None def get_active_tab_url() -> Optional[str]: app = _frontmost_app() if not app: return None if app in _CHROMIUM: return _osascript(f'tell application "{app}" to get URL of active tab of front window') if app == "Safari": return _osascript('tell application "Safari" to get URL of front document') return None