hammerspoon

How can I prevent hammerspoon hotkeys from overriding hotkeys in other applications?


I'm looking at having a certain hotkey only available in Google Chrome:

hs.hotkey.bind({"cmd"}, "0", function()
  if hs.window.focusedWindow():application():name() == 'Google Chrome' then
    hs.eventtap.keyStrokes("000000000000000000")
  end
end)

The issue with this approach is the hotkey will become un-usable on other apps. E.g. CMD+0 will not trigger the Reset Zoom command in Discord.

How can I prevent that?


Solution

  • The hs.hotkey API doesn't provide functionality to be able to propagate the captured keydown event. The hs.eventtap API does, but using it would involve watching for every keyDown event.

    I'll point to what is mentioned in a somewhat related GitHub issue:

    If you're wanting the key combo to do something for most applications, but not for a few specific ones, you're better off using a window filter or application watcher and enabling/disabling the hotkey(s) when the active application changes.

    In other words, for what you're trying to achieve, it's recommended you use the hs.window.filter API to enable the hotkey binding when entering the application, and disable it when leaving the application, i.e. something like:

    -- Create a new hotkey
    local yourHotkey = hs.hotkey.new({ "cmd" }, "0", function()
        hs.eventtap.keyStrokes("000000000000000000")
    end)
    
    -- Initialize a Google Chrome window filter
    local GoogleChromeWF = hs.window.filter.new("Google Chrome")
    
    -- Subscribe to when your Google Chrome window is focused and unfocused
    GoogleChromeWF
        :subscribe(hs.window.filter.windowFocused, function()
            -- Enable hotkey in Google Chrome
            yourHotkey:enable()
        end)
        :subscribe(hs.window.filter.windowUnfocused, function()
            -- Disable hotkey when focusing out of Google Chrome
            yourHotkey:disable()
        end)