Paste a URL That's Open in Safari Without Switching to Safari

During the course of my workday, I paste dozens of web links into emails, Slack messages, iMessages, and my personal notes. I hate having to ⌘+Tab to Safari, hunt for the tab I need, navigate to the address bar, highlight & copy the tab’s URL, and then ⌘+Tab back to the app I was using and paste the link. This sort of context switching often interrupts my writing flow and train of thought.

To make this workflow a little bit easier, I devised a simple, but effective, TextExpander script snippet to grab the URL of the active tab in the front-most Safari window. Here it is:

tell application "Safari" to get URL of front document

This is useful most of the time, however there are instances when I’d like to get a list of all my open Safari tabs and pick the one I’d like to paste. With a little bit of AppleScript and Keyboard Maestro magic, this is pretty easy to accomplish.

Here’s the AppleScript I authored to be run by a Keyboard Maestro macro that’s triggered by typing some text (in my case “.turl”):

-- Get a list of tabs in Safari
tell application "Safari"
  set _tabNames to {}
  set _tabURLs to {}
  set _frontTabName to name of front document
  
  -- Create a list of URLs separated by window
  set _windows to every window whose visible is true
  repeat with _window in _windows
    set end of _tabNames to "----------"
    set end of _tabURLs to ""
    
    repeat with _tab in _window's tabs
      set end of _tabNames to name of _tab
      set end of _tabURLs to URL of _tab
    end repeat
  end repeat
  set end of _tabNames to "----------"
  set end of _tabURLs to ""
end tell

-- Pick from the list of open tabs and output the choset tab's URL
set _currApp to (path to frontmost application as Unicode text)
tell application _currApp
  activate
  choose from list _tabNames with title "Safari Tabs" default items _frontTabName
  if result is not false then
    set _tabChoice to item 1 of result
  else
    return
  end if
  
  repeat with _i from 1 to the count of _tabNames
    if item _i of _tabNames is _tabChoice then return item _i of _tabURLs
  end repeat
end tell

For reference, here’s a screenshot of the macro I built in Keyboard Maestro:

Note: The script action needs to be set to “Type Results” upon successful execution.

Hopefully these two shortcuts designed to grab a link from Safari will help you as they have helped me stay in the flow and save a little bit of time in the process.

1 Like

Here’s what I use to grab the single url without switching and paste it using the token %SafariURL%:

1 Like