API Docs

Monitor and synthesise macOS input events: keyboard, mouse, and scroll wheel.

All coordinate parameters use Hammerspoon screen coordinates: the origin (0, 0) is at the top-left of the primary display and y increases downward, matching hs.screen.

Tapping events

const tap = hs.eventtap.addWatcher(
    [hs.eventtap.eventTypes.keyDown],
    (event) => {
        console.log("Key pressed: " + event.keyCode)
        return hs.eventtap.emit   // pass the event through
    }
)
tap.start()

Suppressing events

Returning hs.eventtap.consume from the callback prevents the event from reaching other applications:

const blocker = hs.eventtap.addWatcher(
    [hs.eventtap.eventTypes.leftMouseDown],
    (event) => hs.eventtap.consume
)
blocker.start()

Sending events

hs.eventtap.keyStroke(["cmd"], "c")
hs.eventtap.leftClick(500, 300)

Types

This module provides the following types:

Properties

hs.eventtap.eventTypes

{[key: string]: number}
A dictionary mapping event type names to their numeric values. Pass values from this dictionary to `addWatcher()` to specify which events to monitor.

hs.eventtap.modifierFlags

{[key: string]: number}
A dictionary mapping modifier key names to their bitmask values for use with `rawFlags`. Includes generic names (`cmd`, `shift`, `alt`, `ctrl`) and side-specific names (`leftCmd`, `rightCmd`, `leftShift`, `rightShift`, `leftAlt`, `rightAlt`, `leftCtrl`, `rightCtrl`) for distinguishing physical keys.

hs.eventtap.systemKeys

{[key: string]: number}
A dictionary mapping system key names to their numeric codes, for use with `makeSystemKeyEvent()` and `systemKeyStroke()`. System keys are the media, volume, brightness and other special keys that macOS delivers as `systemDefined` events rather than ordinary key events: `SOUND_UP`, `SOUND_DOWN`, `MUTE`, `BRIGHTNESS_UP`, `BRIGHTNESS_DOWN`, `CONTRAST_UP`, `CONTRAST_DOWN`, `POWER`, `LAUNCH_PANEL`, `VIDMIRROR`, `PLAY`, `EJECT`, `NEXT`, `PREVIOUS`, `FAST`, `REWIND`, `ILLUMINATION_UP`, `ILLUMINATION_DOWN`, `ILLUMINATION_TOGGLE`, `CAPS_LOCK`, `HELP` and `NUM_LOCK`.

hs.eventtap.consume

boolean
Return this from an event tap callback to suppress the event (prevent other apps from receiving it).

hs.eventtap.emit

boolean
Return this from an event tap callback to allow the event to pass through to other applications.

hs.eventtap.followsKeyboardLayout

boolean
Whether hotkeys from `bindHotkey()` that were bound with a key name move to a different key when the keyboard layout changes, so that they stay on the key that types that character. Default is true. For example, a hotkey bound to `"w"` matches the key US-ANSI calls `W` while a US layout is active, and the key US-ANSI calls `,` after you switch to Dvorak, since that's where Dvorak types `w`. Hotkeys bound with a numeric key code never move. When false, a hotkey stays on whichever key its name resolved to when it was bound. Setting this back to true moves existing hotkeys to the current layout. This is separate from `hs.hotkey.followsKeyboardLayout`, which controls `hs.hotkey` hotkeys. Avoid binding some hotkeys by key name and others by numeric key code with the same modifiers if you switch layouts. If a hotkey moves onto a key code another hotkey already matches, only the one that was enabled first fires.

Methods

hs.eventtap.addWatcher(types, callback, listenOnly) -> HSEventTap

Create an event tap that calls a function for matching events. Call `.start()` to activate it. The callback receives an `HSEventTapEvent`. For modify taps (`listenOnly` omitted or false), return `hs.eventtap.consume` (false) to suppress the event or `hs.eventtap.emit` (true) to pass it through. For listen-only taps the callback's return value is ignored — events are always delivered to other applications. Requires Accessibility permission.
hs.eventtap.addWatcher(types, callback, listenOnly) -> HSEventTap
Name Type Description
types number[] An array of event type integers from `hs.eventtap.eventTypes`
callback function Function called for each matching event. The return value is only meaningful for modify taps.
listenOnly boolean If true, the tap receives events but cannot modify or suppress them. Omit or pass false for a modify tap (the default).
HSEventTap
An HSEventTap watcher, or null if the tap could not be created
event tap watchers will not be automatically destroyed by JavaScript garbage collection. You *MUST* call `removeWatcher()` if you want to dispose of a watcher.
// Modify tap — can suppress events
const tap = hs.eventtap.addWatcher(
    [hs.eventtap.eventTypes.keyDown],
    (event) => {
        console.log("Key: " + event.keyCode)
        return hs.eventtap.emit
    }
)
tap.start()

// Listen-only tap — events always pass through
const listener = hs.eventtap.addWatcher(
    [hs.eventtap.eventTypes.keyDown],
    (event) => { console.log("Key: " + event.keyCode) },
    true
)
listener.start()

hs.eventtap.removeWatcher(tap) -> None

Stop and remove a previously created watcher
hs.eventtap.removeWatcher(tap) -> None
Name Type Description
tap HSEventTap The HSEventTap returned by `addWatcher`
None
hs.eventtap.removeWatcher(tap)

hs.eventtap.makeKeyEvent(key, isDown, mods) -> HSEventTapEvent

Create a keyboard event If `mods` is given, the event carries exactly those modifiers, whatever modifier keys are held when it's created. It is a single key event: to send a whole keystroke with modifiers to an application, including the modifier key presses some applications need to see, use `hs.eventtap.keyStroke(mods, key, app)`. through the current keyboard layout (see `hs.keycodes.map`), or a numeric virtual key code Omit to keep the modifiers that are currently held.
hs.eventtap.makeKeyEvent(key, isDown, mods) -> HSEventTapEvent
Name Type Description
key any A key name or character (e.g. "a", "space", "return", "f1"), resolved
isDown boolean true for key down, false for key up
mods [String] An array of modifier names (e.g. ["cmd", "shift"]), as accepted by `hs.eventtap.keyStroke()`.
HSEventTapEvent
An HSEventTapEvent, or null if the key name is unknown
const evt = hs.eventtap.makeKeyEvent("a", true, ["cmd"])
evt.post()

hs.eventtap.makeKeyEventWithCode(keyCode, isDown, mods) -> HSEventTapEvent

Create a keyboard event using a raw key code If `mods` is given, the event carries exactly those modifiers, whatever modifier keys are held when it's created. Omit to keep the modifiers that are currently held.
hs.eventtap.makeKeyEventWithCode(keyCode, isDown, mods) -> HSEventTapEvent
Name Type Description
keyCode number A numeric virtual key code
isDown boolean true for key down, false for key up
mods [String] An array of modifier names (e.g. ["cmd", "shift"]), as accepted by `hs.eventtap.keyStroke()`.
HSEventTapEvent
An HSEventTapEvent
const evt = hs.eventtap.makeKeyEventWithCode(0, true, ["ctrl"])  // key code 0 = "a"
evt.post()

hs.eventtap.makeMouseEvent(type, x, y, button) -> HSEventTapEvent

Create a mouse event at the given position. Coordinates are in **Hammerspoon screen coordinates** (top-left origin of the primary display, y increases downward), matching the values returned by `hs.screen`.
hs.eventtap.makeMouseEvent(type, x, y, button) -> HSEventTapEvent
Name Type Description
type number An event type integer from hs.eventtap.eventTypes (e.g. leftMouseDown)
x number Horizontal position in Hammerspoon screen coordinates
y number Vertical position in Hammerspoon screen coordinates
button number Mouse button number (0=left, 1=right, 2=middle)
HSEventTapEvent
An HSEventTapEvent, or null if the event could not be created
const s = hs.screen.primary()
// Click at the centre of the primary screen:
const cx = s.frame.x + s.frame.w / 2
const cy = s.frame.y + s.frame.h / 2
const evt = hs.eventtap.makeMouseEvent(hs.eventtap.eventTypes.leftMouseDown, cx, cy, 0)
evt.post()

hs.eventtap.makeScrollWheelEvent(deltaX, deltaY, x, y) -> HSEventTapEvent

Create a scroll wheel event at the given position. Coordinates are in **Hammerspoon screen coordinates** (top-left origin, y increases downward).
hs.eventtap.makeScrollWheelEvent(deltaX, deltaY, x, y) -> HSEventTapEvent
Name Type Description
deltaX number Horizontal scroll amount in lines (positive = right)
deltaY number Vertical scroll amount in lines (positive = down)
x number Horizontal position in Hammerspoon screen coordinates
y number Vertical position in Hammerspoon screen coordinates
HSEventTapEvent
An HSEventTapEvent, or null if the event could not be created
const evt = hs.eventtap.makeScrollWheelEvent(0, 3, 500, 400)
evt.post()

hs.eventtap.makeSystemKeyEvent(key, isDown) -> HSEventTapEvent

Create a system key event, such as a media, volume or brightness key. Posting these behaves like pressing the key on an Apple keyboard, so media keys are routed to whichever app macOS considers to be playing (including audio in a browser tab). Synthetic brightness keys are ignored by some Macs and external displays; use `hs.screen` to set brightness directly if they have no effect.
hs.eventtap.makeSystemKeyEvent(key, isDown) -> HSEventTapEvent
Name Type Description
key string A system key name from `hs.eventtap.systemKeys` (e.g. "PLAY", "SOUND_UP"), case-insensitive
isDown boolean true for key down, false for key up
HSEventTapEvent
An HSEventTapEvent, or null if the key name is unknown
hs.eventtap.makeSystemKeyEvent("PLAY", true).post()
hs.eventtap.makeSystemKeyEvent("PLAY", false).post()

hs.eventtap.keyStroke(mods, key, app) -> None

Send a key down and key up event with optional modifier keys, optionally to a specific application. A 5 ms pause is inserted between the key-down and key-up events to improve compatibility with applications that miss very fast synthetic keystrokes. Without `app`, the keystroke is posted to the system, so it goes to whichever application is frontmost. With `app`, it is delivered straight to that application, even if it's in the background, without activating it. In that case the modifier keys are also pressed and released around the key, as a real keyboard does, so applications that track modifier key presses themselves see them held. through the current keyboard layout (see `hs.keycodes.map`), or a numeric virtual key code, which always presses the same physical key send it to the frontmost application.
hs.eventtap.keyStroke(mods, key, app) -> None
Name Type Description
mods string[] An array of modifier names (e.g. ["cmd", "shift"])
key any A key name or character (e.g. "a", "space", "return"), resolved
app HSApplication The application to send the keystroke to. Omit, or pass null, to
None
hs.eventtap.keyStroke(["cmd"], "c")      // Copy
hs.eventtap.keyStroke(["cmd", "shift"], "4")  // Screenshot selection
hs.eventtap.keyStroke(["ctrl"], 0)       // Ctrl + the key US-ANSI calls A, on any layout

// Reload Firefox without bringing it to the front
const firefox = hs.application.fromBundleID("org.mozilla.firefox")
if (firefox) hs.eventtap.keyStroke(["cmd"], "r", firefox)

hs.eventtap.keyStrokes(text) -> None

Type a string of characters as individual key events. A 5 ms pause is inserted between each key-down and key-up event. This blocks the calling thread (the main thread) for the duration of typing — for long strings, prefer `keyStrokesAsync()` to avoid stalling the rest of Hammerspoon while typing.
hs.eventtap.keyStrokes(text) -> None
Name Type Description
text string The string to type
None
hs.eventtap.keyStrokes("Hello, World!")

hs.eventtap.keyStrokesAsync(text) -> Promise<void>

Type a string of characters as individual key events, without blocking the main thread. Behaves like `keyStrokes()`, but the key events are posted from a background task, so JavaScript execution and the rest of Hammerspoon continue running while typing proceeds.
hs.eventtap.keyStrokesAsync(text) -> Promise<void>
Name Type Description
text string The string to type
Promise<void>
A Promise that resolves once every character has been posted.
await hs.eventtap.keyStrokesAsync("Hello, World!")
console.log("Finished typing")

hs.eventtap.systemKeyStroke(key) -> None

Press and release a system key, such as a media, volume or brightness key. A 5 ms pause is inserted between the key-down and key-up events. See `makeSystemKeyEvent()` for details of how these keys behave. Be careful with `POWER` and `EJECT`, which can show a shutdown prompt or eject media.
hs.eventtap.systemKeyStroke(key) -> None
Name Type Description
key string A system key name from `hs.eventtap.systemKeys` (e.g. "PLAY", "NEXT"), case-insensitive
None
hs.eventtap.systemKeyStroke("PLAY")       // Play/pause whatever is playing
hs.eventtap.systemKeyStroke("SOUND_UP")   // Raise the volume, showing the system HUD

hs.eventtap.leftClick(x, y) -> None

Post a left mouse button click at the given position. Coordinates are in **Hammerspoon screen coordinates** (top-left origin, y increases downward).
hs.eventtap.leftClick(x, y) -> None
Name Type Description
x number Horizontal position in Hammerspoon screen coordinates
y number Vertical position in Hammerspoon screen coordinates
None
hs.eventtap.leftClick(400, 300)

hs.eventtap.rightClick(x, y) -> None

Post a right mouse button click at the given position. Coordinates are in **Hammerspoon screen coordinates** (top-left origin, y increases downward).
hs.eventtap.rightClick(x, y) -> None
Name Type Description
x number Horizontal position in Hammerspoon screen coordinates
y number Vertical position in Hammerspoon screen coordinates
None
hs.eventtap.rightClick(400, 300)

hs.eventtap.doubleLeftClick(x, y) -> None

Post a left mouse button double-click at the given position. Coordinates are in **Hammerspoon screen coordinates** (top-left origin, y increases downward).
hs.eventtap.doubleLeftClick(x, y) -> None
Name Type Description
x number Horizontal position in Hammerspoon screen coordinates
y number Vertical position in Hammerspoon screen coordinates
None
hs.eventtap.doubleLeftClick(400, 300)

hs.eventtap.middleClick(x, y) -> None

Post a middle mouse button click at the given position. Coordinates are in **Hammerspoon screen coordinates** (top-left origin, y increases downward).
hs.eventtap.middleClick(x, y) -> None
Name Type Description
x number Horizontal position in Hammerspoon screen coordinates
y number Vertical position in Hammerspoon screen coordinates
None
hs.eventtap.middleClick(400, 300)

hs.eventtap.scrollWheel(deltaX, deltaY, x, y) -> None

Post a scroll wheel event at the given position. Coordinates are in **Hammerspoon screen coordinates** (top-left origin, y increases downward).
hs.eventtap.scrollWheel(deltaX, deltaY, x, y) -> None
Name Type Description
deltaX number Horizontal scroll amount in lines (positive = right)
deltaY number Vertical scroll amount in lines (positive = down)
x number Horizontal position in Hammerspoon screen coordinates
y number Vertical position in Hammerspoon screen coordinates
None
hs.eventtap.scrollWheel(0, 3, 500, 400)  // Scroll down 3 lines

hs.eventtap.currentModifiers() -> string[]

Returns the currently held modifier keys
hs.eventtap.currentModifiers() -> string[]
string[]
An array of modifier key names such as ["cmd", "shift"]
const mods = hs.eventtap.currentModifiers()
if (mods.includes("cmd")) console.log("Cmd is held")

hs.eventtap.checkMouseButtons() -> {[key: string]: boolean}

Returns the currently pressed mouse buttons
hs.eventtap.checkMouseButtons() -> {[key: string]: boolean}
{[key: string]: boolean}
A dictionary with keys "left", "right", "middle" mapping to booleans
const buttons = hs.eventtap.checkMouseButtons()
if (buttons.left) console.log("Left button held")

hs.eventtap.mouseLocation() -> {[key: string]: number}

Returns the current mouse cursor position in Hammerspoon screen coordinates (top-left origin of primary display, y increases downward, matching hs.screen).
hs.eventtap.mouseLocation() -> {[key: string]: number}
{[key: string]: number}
A dictionary with "x" and "y" keys
const pos = hs.eventtap.mouseLocation()
console.log("Mouse at " + pos.x + ", " + pos.y)

hs.eventtap.doubleClickInterval() -> number

Returns the system double-click interval in seconds
hs.eventtap.doubleClickInterval() -> number
number
The maximum time between clicks that counts as a double-click
console.log("Double-click interval: " + hs.eventtap.doubleClickInterval())

hs.eventtap.keyRepeatDelay() -> number

Returns the system key repeat delay in seconds
hs.eventtap.keyRepeatDelay() -> number
number
The delay before key repeat begins
console.log("Key repeat delay: " + hs.eventtap.keyRepeatDelay())

hs.eventtap.keyRepeatInterval() -> number

Returns the system key repeat interval in seconds
hs.eventtap.keyRepeatInterval() -> number
number
The interval between repeated key events
console.log("Key repeat interval: " + hs.eventtap.keyRepeatInterval())

hs.eventtap.isSecureInputEnabled() -> boolean

Returns whether Secure Input is currently turned on. While Secure Input is on, macOS hides keystrokes from other apps, so `hs.eventtap` watchers and hotkeys see no key events. Apps turn it on for password fields, and some apps (terminals, password managers) can leave it on by mistake.
hs.eventtap.isSecureInputEnabled() -> boolean
boolean
`true` if any process has Secure Input turned on, otherwise `false`
if (hs.eventtap.isSecureInputEnabled()) {
    console.warn("Secure Input is on; keyboard event taps won't see keystrokes")
}

hs.eventtap.secureInputPID() -> number | null

Returns the process ID of an app that has Secure Input turned on, to help track down which app is blocking keystrokes. macOS doesn't document this value. When more than one process has Secure Input on, only one of them is reported, and it isn't always the one that turned it on most recently, so treat it as a starting point rather than a definitive answer.
hs.eventtap.secureInputPID() -> number | null
number | null
A process ID, or `null` if Secure Input is off or macOS doesn't say which process has it
const pid = hs.eventtap.secureInputPID()
if (pid !== null) {
    const app = hs.application.fromPID(pid)
    console.warn("Secure Input is on, probably because of " + (app ? app.name : "PID " + pid))
}

hs.eventtap.bindHotkey(mods, key, onPressed, onReleased) -> HSEventTapHotkey

Bind a keyboard shortcut using an event tap. Unlike `hs.hotkey.bind()`, this supports the `fn` modifier and left/right modifier key distinction (e.g. `leftCmd`, `rightAlt`). The hotkey is active immediately and consumes (suppresses) the key events. It's important to note that this a much heavier-weight tool than `hs.hotkey` - every single key you press will be examined by Hammerspoon to see if it matches one of the EventTap hotkeys (where `hs.hotkey` relies on macOS to efficiently deliver only matching keypresses). Please consider this when choosing to use `hs.eventtap` for hotkeys. Requires Accessibility permission. `ctrl`, `fn`) and side-specific names (`leftCmd`, `rightCmd`, `leftAlt`, `rightAlt`, `leftCtrl`, `rightCtrl`, `leftShift`, `rightShift`). macOS reports `fn` as held on every press of the arrow keys, F-keys, help, home, end, page up/down, forward delete and keypad clear, so on those keys a hotkey with `fn` also fires without it (one without `fn` still works). current keyboard layout (see `hs.eventtap.followsKeyboardLayout`), or a numeric virtual key code, which always means the same physical key each key repeat while the whole combination stays held, or null repeat shows the combination is no longer held (e.g. a modifier was let go first), or null. After that, the key's remaining repeats and its release pass through as normal.
hs.eventtap.bindHotkey(mods, key, onPressed, onReleased) -> HSEventTapHotkey
Name Type Description
mods string[] An array of modifier key strings. Supports generic names (`cmd`, `shift`, `alt`,
key any A key name or character (e.g., "a", "space", "f1"), resolved through the
onPressed function Called when the key combination is pressed, and again for
onReleased function Called when the key is released, or as soon as a key
HSEventTapHotkey
An `HSEventTapHotkey` object, or null if binding failed
The hotkey stays bound until you disable it, even if you don't keep a reference to it.
// Bind Fn+F1 — not possible with hs.hotkey
const hk = hs.eventtap.bindHotkey(["fn"], "f1", () => {
    console.log("Fn+F1 pressed!")
}, null)

// Bind left-Cmd+H only (right Cmd+H passes through)
const hk2 = hs.eventtap.bindHotkey(["leftCmd"], "h", () => {
    console.log("Left Cmd+H!")
}, null)

hs.eventtap.removeHotkey(hotkey) -> None

Remove a previously bound hotkey and stop it from firing
hs.eventtap.removeHotkey(hotkey) -> None
Name Type Description
hotkey HSEventTapHotkey The HSEventTapHotkey returned by `bindHotkey`
None
const hk = hs.eventtap.bindHotkey(["fn"], "f1", () => {}, null)
hs.eventtap.removeHotkey(hk)