MacOS – How to get a list of application windows only from the current desktop with applescript

applescriptdesktopmacosspaces

Need to do something like the next

tell application "Safari"
activate
    set AllWindows to every window
    set WinCount to number of items in AllWindows

    repeat with i from 1 to WinCount
        set this_window to item i of AllWindows
        -- do something with the this_window
    end repeat
end tell

The abowe work ok, and getting ALL opened opened Safari window.

How can get the windows only from the curent desktop? So need somewhat change the line

    set AllWindows to every window

to something like

    set AllWindows to ONLY FROM THE CURRENT desktop windows :)

Any idea?

Best Answer

System Events only includes windows in the current space / desktop:

tell application "System Events" to windows of process "Safari"

I don't know any way to convert a System Events window object to a Safari window object though, apart from hacks like this:

tell application "System Events" to tell window 1 of process "Safari"
    set {x, y} to position
    set {w, h} to size
    set b to {x, y, x + w, y + h}
    set t to title
end tell
tell application "Safari"
    set found to missing value
    repeat with w in windows
        if bounds of w is b and name of w is t then
            set found to w
            exit repeat
        end if
    end repeat
    found
end tell

tell application "System Events" to value of attribute "AXIdentifier" of window 1 of process "Safari" does not correspond to tell application "Safari" to id of window 1.