Hammerspoon (JavaScript API)
Hammerspoon is a macOS app that runs the user's JavaScript (JavaScriptCore) and exposes system
APIs under the global hs object. This skill covers that JavaScript API.
Read this first: memory is not a reliable source here
Most Hammerspoon code on the web and in your training data is written in Lua for a different,
older API. None of it runs here. Lua syntax (function() ... end, obj:method(), {"cmd"}
tables), and modules such as hs.alert, hs.logger, hs.grid or hs.caffeinate, cause errors
in this runtime. Many names look familiar but have different signatures.
So: check every hs.* call you write against the API reference before you give it to the
user. If a call isn't in the reference, don't use it. See "Looking things up" below.
Present this API simply as Hammerspoon. Don't compare it with other versions or add migration notes unless the user asks.
Common replacements for names that don't exist here:
| Don't write | Use instead |
|---|---|
hs.alert.show(msg) | hs.ui.alert(msg).duration(2).show() |
hs.logger, print | console.log/.warn/.error/.info/.debug |
hs.grid, hs.layout, moveToUnit | win.frame = unitRect.fromUnitRect(win.screen.frame) with an HSRect |
hs.geometry | new HSRect(x, y, w, h), new HSPoint(x, y), new HSSize(w, h) |
hs.caffeinate, hs.battery | hs.power (preventSleep, lockScreen, percentage, ...) |
hs.drawing | hs.canvas (absolute drawing) or hs.ui (layout UI) |
hs.webview | hs.ui.webview() |
hs.settings | hs.userdefaults |
hs.execute(cmd) | hs.task.shell(cmd).then(r => r.stdout) |
hs.json, hs.inspect | JSON.parse/stringify, require('util').inspect |
hs.base64 | hs.hashing.base64Encode/base64Decode |
hs.image | HSImage.fromPath/fromSymbol/fromAppBundle/... |
hs.spaces | HSSpace via hs.screen and hs.window |
hs.loadSpoon(...) | hs.spoons.load(...) or hs.spoons.use(...) |
Looking things up
-
Docs site. Fetch the page with the web fetch tool and ask for the exact signatures, parameter types, return values and examples of the members you need:
- module:
https://www.hammerspoon.org/2/main/js/<module>.html(for examplehttps://www.hammerspoon.org/2/main/js/hs.window.html) - object type:
https://www.hammerspoon.org/2/main/js/<Type>.html(for examplehttps://www.hammerspoon.org/2/main/js/HSWindow.html) - guides:
getting-started.html,canvas-guide.html,spoons-guide.htmlandtypescript-guide.htmlunderhttps://www.hammerspoon.org/2/main/js/
- module:
-
Installed docs.
hs.docs.show()opens the offline docs of the installed version. Use it when the site is unreachable or the user's version may differ.A module's object types have their own pages, so fetch both the module page and the type page. The fetch returns a summary, so ask for exact signatures. If a detail is still missing, rely on the page's examples and tell the user which detail you couldn't confirm.
Workflow
- Work out which modules the task needs, using the module table below.
- Look up those modules (see above). Read a guide when the task is mainly about its topic.
- Write the code following the conventions below.
- Before answering, check each
hs.*call, its argument order and its return type (property or method? Promise or value? can it returnnull?) against the reference. - Give complete, runnable code that can go in
init.js, or in a fileinit.jsrequires. Mention any macOS permission it needs (see Permissions).
Runtime essentials
Config. One file, init.js, in the config directory (usually ~/.config/Hammerspoon2/;
hs.appinfo.configPath and hs.appinfo.configDir give the exact paths). It runs top to bottom
once, at launch and on each reload. There is no entry-point function. Reload with "Reload
Config" in the menu bar icon or hs.reload(). hs.openConsole() shows the log and REPL;
uncaught exceptions appear there with file and line. hs.docs.show() opens the offline docs.
Object lifetime (the most important rule). Anything running keeps running, with its
callbacks, until it finishes or is stopped, whether or not a reference is kept: bound hotkeys,
started timers, watchers, event taps, running tasks, shown windows, canvases, choosers, menu bar
items and sounds. Dropping a reference does not stop anything. Call stop(), disable(),
hide(), terminate() or destroy() instead. So keep a reference (a top-level const) to
anything you might stop, update or re-show later. That includes reactive values that feed a UI.
Objects that are not running (a timer never started, a hidden window) are garbage collected like
any JS value. hs.reload() stops everything. hs.activeObjects() lists what is running.
Events: on / off / once. Modules that report state changes take the event name first:
hs.application.on('didLaunch', app => ...). These include hs.application, hs.audiodevice,
hs.camera, hs.distributednotifications, hs.keycodes, hs.locale, hs.pasteboard,
hs.power, hs.screen, hs.serial, hs.streamdeck, hs.usb, hs.userdefaults, hs.wifi and
hs.windowfilter. Look up the exact event names in the module's reference. off() matches by
function identity, so keep the function if you'll remove it. If the underlying watcher can't
start, on() throws and registers nothing. Wrap it in try/catch when the config must keep
going. hs.ax.on(element, notification, listener) uses a different argument order. A few
modules return a watcher object to configure and start() instead: hs.fs.createPathWatcher(),
hs.eventtap.addWatcher() and hs.location.
Promises. Slow operations return Promises instead of taking callbacks. Examples are
AppleScript, HTTP, hs.application.launchOrFocus(bundleID), hs.task.shell and
hs.spoons.use. hs.osascript.applescript() always resolves: check result.success. Other
modules reject on failure. Check the reference. Signatures shown as Promise<any> | null resolve
to whatever the member's doc describes.
Properties vs methods. Many values are properties, not methods: win.title, win.frame,
win.screen, win.application, app.name, app.bundleID, screen.frame. Settable ones are
assigned: win.frame = rect. The signature in the reference shows which is which (readonly
means not settable).
Geometry. Screen coordinates start at the top-left of the primary display, with y
increasing downward. screen.frame excludes the menu bar and Dock; fullFrame includes them.
HSRect has fromUnitRect(frame) / toUnitRect(frame) for fractional layouts:
const LEFT_HALF = new HSRect(0, 0, 0.5, 1)
hs.hotkey.bind(["cmd", "alt"], "left", () => {
const win = hs.window.focusedWindow()
if (win) win.frame = LEFT_HALF.fromUnitRect(win.screen.frame)
})
Hotkeys. hs.hotkey.bind(mods, key, onPressed, onReleased?, onRepeat?) returns an HSHotkey,
or null if binding failed. bindSpec({mods, key, pressed, released, repeat, message}) takes a
single options object. createModal(mods, key) creates a modal group. Mods are strings such as
"cmd", "alt", "ctrl" and "shift".
UI. hs.ui is a chained, declarative SwiftUI builder: hs.ui.window({x, y, w, h}), then
containers (.vstack() / .hstack() / .zstack(), each closed with .end()), content
(.text(), .button(), .image(), ...), modifiers that apply to the previous element
(.font(), .frame(), .onClick(), ...), and finally .show(). To change content after the
window is shown, pass a reactive value (hs.ui.string(...), HSColor, HSImage) and call
.set() on it later. To change the window's structure, build a new window. Use hs.ui.alert,
.dialog, .textPrompt and .filePicker for standard UI. Use hs.canvas for
absolutely positioned drawing (overlays, shapes, gradients, click-through). Canvas elements are
plain objects. In canvas colors, an omitted alpha defaults to 1 ({alpha: 1} is opaque black).
Splitting config. require("./file.js") works like Node's require: module.exports, a
required ./ or ../ prefix for local files, optional .js, index.js for directories, parsed
.json, and caching by path. Each required file has private scope. Only init.js runs at global
scope. require('util') and require('node:sqlite') are also available (see
the node page on the docs site).
Permissions. Window, accessibility, application-UI and event-tap features need
Accessibility permission. Screen and window snapshots need Screen Recording. Other permissions
are noted on the members that need them. hs.permissions can check and request each permission
(checkAccessibility(), requestAccessibility(), ...). When a feature needs a permission, say so.
Module table
On the docs site, each module and each type has its own page. The last column lists the object types that belong to the module.
| Module | Use it for | Object types in the same file |
|---|---|---|
hs | reload, console, activeObjects(), onRelaunch, onOpenFile, accessibilityTimeout | |
console | console.log and related functions | |
hs.appinfo | Hammerspoon's version, config paths | |
hs.application | running apps, launch or focus, hide, menus, app events | HSApplication |
hs.audiodevice | audio input and output devices, volume, mute | HSAudioDevice |
hs.ax | raw Accessibility elements and notifications | HSAXElement |
hs.bluetooth | Bluetooth devices and BLE peripherals | HSBluetoothDevice, HSBluetoothPeripheral |
hs.bonjour | discover and publish mDNS services | HSBonjourSearch, HSBonjourService |
hs.camera | cameras and in-use events | HSCamera |
hs.canvas | absolutely positioned drawing and overlays | HSCanvas |
hs.chooser | Spotlight-style fuzzy picker | HSChooser |
hs.distributednotifications | post and receive distributed notifications | |
hs.dockicon | Hammerspoon's own Dock icon | |
hs.docs | open the bundled API docs | |
hs.eventtap | watch, suppress and synthesize keyboard, mouse and scroll events; keystrokes | HSEventTap, HSEventTapEvent, HSEventTapHotkey |
hs.fs | files, directories, attributes, file handles, path and volume watchers | HSFile, HSPathWatcher, HSVolumeWatcher |
hs.hashing | hashes, HMAC, base64 | |
hs.hotkey | global hotkeys, modal hotkeys | HSHotkey, HSHotkeyModal (JS) |
hs.http | HTTP client, WebSocket client | HSWebSocket |
hs.httpserver | HTTP and WebSocket server | HSHTTPServer, HSWebSocketConnection |
hs.ipc | the hs2 command-line tool | |
hs.keyboard | Caps Lock, LEDs, attached keyboards | |
hs.keycodes | keyboard layouts, input sources, key codes | |
hs.locale | language and region settings | |
hs.location | Location Services, geocoding, sunrise and sunset | HSLocationWatcher, HSLocationGeocoder |
hs.menubar | menu bar items and menus | HSMenuBarItem |
hs.midi | MIDI devices and messages | HSMIDIDevice |
hs.mouse | pointer position, tracking speed, cursor | |
hs.mqtt | MQTT client | HSMQTTClient |
hs.network | interfaces, DNS, reachability, ping, network configuration watching | HSNetworkPing, HSNetworkReachability, HSNetworkConfigurationWatcher |
hs.notify | macOS notifications | HSNotification |
hs.ocr | text recognition in images | HSOCRResult, HSOCRObservation |
hs.osascript | run AppleScript and JXA | |
hs.pasteboard | clipboard read, write and change events | |
hs.permissions | check and request TCC permissions | |
hs.plist | read and write plist files | |
hs.power | prevent sleep, lock, battery, power and session events | |
hs.screen | displays, modes, screenshots, Spaces, Mission Control | HSScreen, HSSpace |
hs.serial | serial ports | HSSerialPort |
hs.sharing | macOS share services | HSSharingService |
hs.shortcuts | run Shortcuts | |
hs.socket | TCP, UDP and Unix sockets | HSSocket, HSUDPSocket, HSUnixDatagramSocket |
hs.sound | play sounds | HSSound |
hs.spoons | install, load and use Spoons | |
hs.spotlight | Spotlight metadata queries | HSSpotlightQuery, HSSpotlightItem, HSSpotlightGroup |
hs.streamdeck | Elgato Stream Deck hardware | HSStreamDeckDevice |
hs.task | run processes (shell, runAsync, builder) | HSTask, TaskBuilder (JS) |
hs.timer | one-shot, repeating and time-of-day timers | HSTimer |
hs.translation | on-device translation | HSTranslationSession |
hs.ui | windows built from stacks, alerts, dialogs, prompts, file pickers, web views | HSUIWindow, HSUIAlert, HSUIDialog, HSUITextPrompt, HSUIFilePicker, UIWebView |
hs.urlevent | handle hammerspoon2:// URLs | |
hs.usb | USB attach and detach events | |
hs.userdefaults | small persistent key/value storage | |
hs.wifi | Wi-Fi state, scanning, events | |
hs.window | find, move, resize and focus windows | HSWindow |
hs.windowfilter | filtered window sets and window events | HSWindowFilter |
node (file) | require('util'), require('node:sqlite') | DatabaseSync, StatementSync, StatementSyncIterator |
The value types shared by all modules are HSRect, HSPoint, HSSize, HSColor, HSFont,
HSImage, HSString and HSVideo (docs site: one page each).
Some modules have a "JavaScript additions" section. Those members are written in JS on top of
the native module (for example hs.hotkey.bindSpec, hs.window.moveToLeftHalf,
hs.task.shell) and work like any other member.
Guides
Read these for narrative explanations and worked examples. Each is a page under
https://www.hammerspoon.org/2/main/js/.
getting-started.html: config file, lifetime, hotkeys, watchers, Promises, windows,hs.ui,require. Read it for any task that builds a config from scratch.canvas-guide.html: the canvas element dictionaries (types, actions, colors, gradients, clipping) and demos. Method signatures alone aren't enough for canvas work.spoons-guide.html: installing, using and writing Spoons (.spoon2bundles,spoon.json,bindings, lifecycle).typescript-guide.html: writing the config in TypeScript withhammerspoon.d.ts.
Source
Based on the Hammerspoon 2 source and docs (https://github.com/Hammerspoon/Hammerspoon2,
MIT licence). The live reference is at https://www.hammerspoon.org/2/main/js/index.html.
If the user's installed version behaves differently from these references, trust the app:
hs.docs.show() always matches the installed version.