Getting URL and Tab Title from Firefox with AppleScript

A long time ago, a coworker shared an AppleScript function that gets the title and URL from the current tab in Chrome and formats the result as an Emacs org mode link.

Org mode links have the format [[url][title]], e.g.:

[[][· Matt's programming blog]]

Invoked via Alfred, this script was helpful for getting links from Github pull requests, Trello cards, etc. into my org TODO list. When I began using Firefox Quantum, however, the Chrome-specific script was of no use.

Firefox does not have AppleScript support, which means that any automated interaction with the application must be clumsily achieved through simulating GUI events. I found out that such GUI-based automation is prone to failure. It took some trial and error and cobbling various online snippets together, but so far this script has been fairly robust:

use scripting additions
use framework "Foundation"

tell application "Firefox" to activate

-- get the tab title from FF
tell application "System Events" to tell process "firefox"
	set frontmost to true
	set the_title to name of windows's item 1
	set the_title to (do shell script "echo " & quoted form of the_title & " | tr '[' ' '")
	set the_title to (do shell script "echo " & quoted form of the_title & " | tr ']' ' '")
end tell

set thePasteboard to current application's NSPasteboard's generalPasteboard()
set theCount to thePasteboard's changeCount()

-- send cmd+l and cmd+c keystrokes to FF to highlight and copy the URL
tell application "System Events"
	keystroke "l" using {command down}
	delay 0.2
	keystroke "c" using {command down}
end tell

-- wait for the clipboard content change to have been detected
repeat 20 times
	if thePasteboard's changeCount() is not theCount then exit repeat
	delay 0.1
end repeat

-- get the clipboard contents
set the_url to the clipboard

return "[[" & the_url & "][" & the_title & "]]" as text