For some reason I can’t seem to find, this doesn’t work (and it’s one of many variations). It fails because it fails to close the frontmost tab with the Command-w even though that works from the keyboard.
set theURLs to {}
try
repeat
tell application "Safari"
activate
set end of theURLs to URL of document 1
tell document 1
using terms from application "System Events"
keystroke w using {command down}
end using terms from
end tell
end tell
end repeat
on error
exit repeat
end try
theURLs
This is where Script Editor gets somewhat less than friendly. It requires one to really squint and look at the colors and shapes of the markup it returns to the editor after compile time. In this case your w is being ‘seen’ as a variable as opposed to a string. It needs to be a string to work correctly, so that means quotes:
tell application "System Events" to keystroke "w" using command down
Since I have a lot of open tabs at the moment that I don’t feel like closing, I repurposed said script a bit so that it gets all the tab URLs first, and then closes the whole window at once. Adjust as necessary:
set theURLs to {}
tell application "Safari"
activate
repeat
set an_url to URL of the front document
if an_url is not in theURLs then
set end of theURLs to an_url
tell application "System Events" to keystroke "}" using command down
else
exit repeat
end if
end repeat
end tell
tell application "System Events" to keystroke "w" using {shift down, command down}
theURLs