Skip to content

Instantly share code, notes, and snippets.

@rppig42
Last active November 29, 2024 04:42
Show Gist options
  • Select an option

  • Save rppig42/c121b11284cea7fe5d17f08656a8d556 to your computer and use it in GitHub Desktop.

Select an option

Save rppig42/c121b11284cea7fe5d17f08656a8d556 to your computer and use it in GitHub Desktop.
hammerspoon script to prevent safari closing window with cmd+w
script = [[
tell application "Safari"
set numWin to count of tabs of window 1
if numWin > 1 then
close current tab of front window
end if
if numWin = 1 then
tell application "System Events"
keystroke "t" using command down
end tell
tell window 1 of application "Safari"
close (tabs where index < (get index of current tab))
end tell
end if
end tell
]]
local targetApp = "Safari"
local appHotkeyModal = hs.hotkey.modal.new()
local function activateHotkeys()
local frontApp = hs.application.frontmostApplication()
if frontApp and frontApp:name() == targetApp then
appHotkeyModal:enter()
else
appHotkeyModal:exit()
end
end
-- Bind the hotkey in the modal
appHotkeyModal:bind({"cmd"}, "w", function()
hs.alert.show("Hotkey triggered in " .. targetApp)
hs.applescript(script)
end)
-- Watch for app focus changes
local appWatcher = hs.application.watcher.new(function(name, eventType, appObject)
if eventType == hs.application.watcher.activated then
activateHotkeys()
end
end)
-- Start the app watcher
appWatcher:start()
-- Activate the hotkeys initially if the app is already focused
activateHotkeys()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment