Navigating the web via page search. In Safari.

Last month I wrote that I switched to Firefox because of its shiny link search. Conveniently mapped to the quote (') key, it makes navigating the web via the keyboard a breeze. Just enter a bit of text you see on the page, watch it light up, press Enter, and boom, you’re off to the next round. No fiddling with your trackpad or (god forbid) a mouse. I’d been enjoying it tremendously. Until I noticed that:

  • Alfred can’t search Firefox bookmarks,
  • muscle memory still makes me launch Safari all the time,
  • my browser-related AppleScripts are broken and Firefox has no AppleScript support.

It may come as a surprise, but only the last one was a deal breaker. I could’ve launched Safari every once in a while to import new bookmarks (therefore exposing them to Alfred), and I would certainly defeat the habit of typing “safari” in Alfred to open the browser, but without AppleScript support I just couldn’t fix a bunch of my custom automations (such as “add current page title/URL to OmniFocus”) and I quickly gave up looking for feasible alternatives. I briefly considered making a Firefox extension, but I strongly suspected that it would be easier to port link navigation to Safari. That proved to be true.

MacOS comes with an app called Automator which offers a function to create custom services: bits of automation that run in a particular context. Now, the AppleScript dictionary exposed by Safari contains a function to run a JavaScript snippet on an open web page. By combining these two bits of knowledge, I wrote a tiny AppleScript and packaged it as an Automator service. If you’re interested to give it a try, feel free to download my pre-packaged version or create one yourself using the script below.

tell application "Safari"
	tell window 1
		tell current tab
			do JavaScript "window.getSelection().anchorNode.parentElement.closest('a,button').click()"
		end tell
	end tell
end tell

Once you install the service, I recommend assigning a convenient shortcut (e.g., ⌘+⇧+return) to the new “Open highlighted link” service in System Preferences (Keyboard > Shortcuts > App Shortcuts, then select Safari). When you try to run it, you might be asked to enable “Allow JavaScript from Apple Events” option in Safari. And that’s it. Now you can search text on web pages and use the new shortcut to click on links and buttons.

An animated image showing the service at work.
Look ma no Firefox