Controlling Browsers With AppleScript

I recently came across a Raycast extension that allows you to play/pause music from YouTube music while it’s running in your browser. After exploring how it worked internally given I was a bit astonished it is even possible, I found that it’s all just using AppleScript.

So, a bit of bash code later and I had a working implementation of a new js command to allow running JavaScript either the active browser tab or in all windows with a given URL.

js
#!/usr/bin/env bash

# Default values
browser="Arc"
url=""
code=""

# Parse the command line args
while [[ $# -gt 0 ]]; do
	case "$1" in
	-b | --browser)
		browser="$2"
		shift 2
		;;
	-u | --url)
		url="$2"
		shift 2
		;;
	*)
		code="$1"
		shift
		;;
	esac
done

_wrap() {
	if [[ -n "$url" ]]; then
		printf "repeat with w in (every window)\n"
		printf "repeat with t in (every tab whose URL contains \"$url\") of w\n"
		printf "tell t\n"
	else
		printf "tell front window\n"
		printf "tell active tab\n"
	fi

	# Run the JS
	printf "$1\n"
	printf "end tell\n"

	if [[ -n "$url" ]]; then
		printf "end repeat\n"
		printf "end repeat\n"
	else
		printf "end tell\n"
	fi
}

osascript -e "
  tell application \"$browser\"
    $(_wrap "execute javascript \"$code\"")
  end tell
" >/dev/null

Here’s the command that will play music from YouTube music like what the Raycast extension was doing. But this now can be a terminal command!

play
js --url music.youtube.com "document.querySelector('#play-pause-button[aria-label=Play]').click()"

Definitely planning on using this more for other areas where I have simple JavaScript I want to execute, such as clicking something after a hot reload, etc.

Chromium security

In Chromium based browsers (e.g. Chrome, Arc), you need to enable a developer flag in order for this to work properly. You can find it in the menu:

View -> Developer -> Allow JavaScript from Apple Events