MacOS – AppleScript, set the position of the frontmost window, even if not AppleScriptable

applescriptmacosscript

I am trying to write a script to center the frontmost window of the active app, when I select this AppleScript from the Script menu in the menu bar. It should work with any app, including non-scriptable apps.

When I run this from Script Editor, it works fine. whether I select the current app or another app from the “tell” application menu in Script Editor, it still sees that the Script Editor is the frontmost app, and moves that window accordingly. (I have also debugged by manually assigning the name of another app to currentApplication, including a non-scriptable app, and that also works fine.)

The trouble seems to be when the script is run from the Script menu item. I have debugged by displaying a notification with the text of currentApplication, and every time it displays the name of the frontmost application, as expected. However, it does not move the position of the window. What gives?

-- Get name of the current application and its front window
tell application "System Events"
    set activeApps to name of application processes whose frontmost is true
    set currentApplication to item 1 of activeApps
    -- DEBUG -- currentApplication seems to be the correct application
    -- display notification currentApplication
    -- activate currentApplication
    -- Get the front window and its measurements
    set frontWindow to the first window of application process currentApplication
    set windowSize to size of frontWindow
    set windowPosition to position of frontWindow
end tell

-- Get the bounds of the screen
tell application "Finder"
    set screenBounds to bounds of window of desktop
end tell

--calculate the center of the current window
set windowSizeX to item 1 of windowSize
set windowSizeY to item 2 of windowSize
set windowCenterX to windowSizeX / 2
set windowCenterY to windowSizeY / 2

-- calculate the center of the screen
set screenCenterX to (item 3 of screenBounds) / 2
set screenCenterY to (item 4 of screenBounds) / 2

--calculate the new window position
set newWindowPositionX to screenCenterX - windowCenterX
set newWindowPositionY to screenCenterY - windowCenterY

-- set the new window position
tell application "System Events"
    set position of frontWindow to {newWindowPositionX, newWindowPositionY}
end tell

Best Answer

The answer was to allow SystemUIServer.app to control the computer, in the Security > Privacy > Accessibility preferences. I had so many Finder windows open, I can only assume that the warning dialogue was popping up behind them. Once the permission is granted, it works fine.

Allow SystemUIServer