Stop Safari from closing window when closing "last" tab

I’ve recently switched back to Safari from Chrome. I have Safari set with a couple of pinned tabs which works great. The only issue I have is that when I use a keyboard shortcut to close regular tabs (Command+W), if there is only one regular tab then it closes the Safari window.

Does anyone know of a way, possibly using AppleScript, to prevent Command+W from ever closing the window. I actually have a separate keyboard shortcut (Command+Shift+W) to close the window. If the last regular tab is closed then I want the window to persist and possibly have a blank tab remaining.


My suggestion would be to go to the General tab in Safari preferences and set a homepage to whatever you choose, then, whenever you’re down to your last tab, hit Command-Shift-H instead of Command-W. That opens whatever you have set for your homepage in preferences.

That sounds like Keyboard Maestro might be able to help them.

If KM can check for the number of tabs left, an IF statement could be used to change the CMD-W into CMD-S-H when there’s only one tab.

Clearly I haven’t tried this, but it sounds plausible to me.

Thanks, but I really don’t want another keyboard shortcut. I use Command+W to close tabs and the problem usually arises when I don’t realize I’m down to my last tab and the window closes.

I’m never used Keyboard Maestro. I’ll give it a look. Thanks.

I highly endorse the use of Keyboard Maestro, and I think @GraemeS’s solution is more clever than mine. But if I had to choose between learning one new shortcut or learning KM just to do one thing? I might choose the shortcut.

If you want to use Keyboard Maestro while keeping ⌘W, this macro in an macro group set to be available only in Safari might help:

I think the behavior you described with ⌘W closing the window is only true when there is more than one Safari window. So this macro checks that first, and then if the frontmost window has less than 2 tabs open, ⌘W will go to your home page set in Safari Preferences (you can change that to a different action within “Execute the following actions”). Otherwise, if there are 2 or more tabs, it will do a traditional ⌘W.

I didn’t test this too extensively, and there may be a more elegant way to do it, but it may point you in the right direction. Here’s the AppleScript:

set W to 0
set T to 0
tell application "Safari"
	set W to count of every window
	if W is greater than 1 then
			set T to count of every tab of window 1
		end try
		set T to 2
	end if
end tell
return T