Oct 26, 2014

If you've developed a Safari extension before, you may feel the same way I do towards the Reload button. Look at it, annoying.

reload

When you make a change in Vim worthy of a reload, you shouldn't have to use a pesky mouse to reload your extension. I got tired of that button so I decided to write a Vim plugin Safariext to press Safari extension builder buttons for me.

  • Reload
  • Inspect Global Page
  • Install
  • Uninstall
  • Build Package...
  • Extension Builder

How It Works

The plugin uses external commands and AppleScript to automatically press the buttons. It takes advantage of Vim's bang command :! to run external commands. Along with silent execute, we can run an external command in the background.

In order to run AppleScript from the command we need osascript -e. This allows AppleScript to be run directly in a bash command. The following activates Safari in the background.

silent execute "!osascript -e 'activate application \"Safari\"'

The AppleScript to press a Safari button looks like the following.

tell application "System Events"
    tell process "Safari"
        click button "Reload" of UI element 3 of UI element 1 of scroll area 1 of window "Extension Builder"
    end tell
end tell

You may notice that clicking the button is not very straightforward, as you must navigate through the containers first. To make this part really easy, I downloaded UI Browser. Xcode now ships with Accessibility Inspector that let's you hover over elements to see their hierarchy, but UI Browser can also give you the exact AppleScript code needed to access the element.

Usage

  • The following commands apply to the extension currently chosen in Safari's extension builder.
    • :SafariextInstall
    • :SafariextUninstall
    • :SafariextReload
    • :SafariextInspectGlobal
    • :SafariextBuild
  • Open Safari extension builder with :SafariextOpen.
  • Each command can be mapped. These are the mappings I use.
  nnoremap <leader>eo :SafariextOpen<cr>
  nnoremap <leader>ei :SafariextInstall<cr>
  nnoremap <leader>eu :SafariextUninstall<cr>
  nnoremap <leader>er :SafariextReload<cr>
  nnoremap <leader>eg :SafariextInspectGlobal<cr>
  nnoremap <leader>eb :SafariextBuild<cr>

Installation

My preferred installation method is Vundle. Install Vundle and add Plugin 'flipxfx/vim-safariext' to your vimrc.

Tips

  • You can keep extension builder hidden behind Safari when using reload.
  • The script does work when Safari is in fullscreen and extension builder is open on another space, but you will need to switch to the Safari window manually.
  • Source code found on Github.