2

Scripting different desktops in recent macOS versions is difficult, but one scenario I wanted to accomplish is to open a document in Safari in a specific window:

  • If a Safari window is open in the current space, open a new tab in that window.
  • Otherwise, make a new window in the current space and open it there.

How can this be accomplished?

3

For some strange reason, in System Events, the windows of a process only include windows on the active space. Using this tidbit, I was able to cobble together a solution to this.

on count_windows_on_current_space(process_name)
    tell application "System Events"
        tell process process_name
            return count of windows
        end tell
    end tell
end count_windows_on_current_space

tell application "Safari"
    if my count_windows_on_current_space("Safari") = 0 then
        make new document
    end if
    open location "https://cgamesplay.com/"
end tell
6
  • 1
    Why within the block of the on count_windows_on_current_space(process_name) handler do you have tell process "Safari" when it should really be tell process process_name? Otherwise when using the handler, e.g. count_windows_on_current_space(TextEdit), the TextEdit process is never queried. May 11 '19 at 11:55
  • 1
    Also, I hate to tell you this, but this does not work properly all the time! For example, two Desktops, the first one has two or more Safari windows, but one of the windows is minimized. Now (before or after fixing the issue pointed out in the first comment) you run your AppleScript code from the second Desktop and it will return 1, not 0 as one might expect. So it's back to the drawing board! May 11 '19 at 11:56
  • I look at this issue a while back and the only solution I could think of using normal basic AppleScript was to check to see if the target App has any minimized windows and restore them first. This caused an issue if the minimized window is on a different Desktop by switching back to that Desktop, which defeated the purpose of what was being done at the time. It also was visually disruptive. May 11 '19 at 12:07
  • Thanks for the insight! I've fixed the code snippets, but you're right. In the future I might try counting non-minimized windows, which in my use case would be fine: if the window is minimized, create a new one. May 11 '19 at 13:50
  • Re: "I might try counting non-minimized windows" ... Then how are you going to tell if the Desktop you're at doesn't have a normal window showing? I've been down that road and because the code you have is't accurate what code would you use? May 11 '19 at 14:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .