Safari close specific tab? (old script just became obsolete)

Quite fed up with Apple constantly breaking scriptability but browser is something that you can’t not update, because of security reasons. Because the syntax changes are so new, it’s harder to find existing threads for solutions now.

I meant to have Safari find a specific tab and close it. I would only ever have one page of that domain open at a time, and the window itself would be minimized. Suddenly this script has stopped working and it fails at row 5, highlighting the expression “tabs where its name is tabName”, result “error “Safari got an error: Can’t make missing value into type document.” number -1700 from missing value to document”.

set tabName to "MacScripter"
tell application "Safari"
	if it is running then
		tell (windows where its document is not missing value)
			set _tabs to tabs where its name is tabName
			repeat with ndx1 in _tabs
				repeat with ndx2 in ndx1
					close ndx2
				end repeat
			end repeat
		end tell
	end if
end tell

“MacScripter” there just for testing. Some other methods that I came across now seem to close the entire window including whatever other tabs there was regardless of talking about tabs instead of windows, and if several windows are open, it will close the frontmost window with its tabs even if the tab that I was trying to close was in a completely different window! :o

What might currently be the functional approach for doing this?

Here is a quickly modified version I just tested.
I am using repeat clauses to cycle through all tabs on all windows


set tabName to "MacScripter"
tell application "Safari"
	if it is not running then return
	set windowlist to windows
	repeat with i in windowlist
		set tablist to tabs of i
		repeat with j in tablist
			if name of j is tabName then
				close j
				return -- I exit out here since it closed the tab already
			end if
		end repeat
	end repeat
end tell

Here is a version using the whose clause to filter tabs


set tabName to "MacScripter"

tell application "Safari"
	if it is not running then return
	set windowlist to windows
	repeat with i in windowlist
		set tablist to (tabs of i whose name is tabName)
		if (count of tablist) > 0 then
			close item 1 of tablist
			return
		end if
	end repeat
end tell

Excellent robertfern , both of these work, thank you!
For both, I just also had to change “name is” to “name contains” instead, because the names of the tabs that I’m trying to find-close vary, but in every case, they still contain the site domain’s name in the title, and that’s a sure identifier. :cool: