Give window focus after bringing it to front by setting its index to 1?

Apparently, or maybe only sometimes, setting a window’s index to 1 to bring it to the front does not give it focus. I could give it focus by clicking its title bar then have the mouse return to its previous position, but I am looking for a more legitimate solution (a script).

I asked about this in another post, and this issue is better pursued in that post’s context. However I didn’t fetch any responses to the comment where it was, so I thought I’d bring it up as a separate topic. If there’s an answer, people will find it more easily on this page than where I made the original comment.

FYI:

Hey Mitchell,

The only fairly reliable (if kludgey) way with AppleScript (not System Events) is to create a new window and close it.

tell application "Safari"
   activate
   make new document with properties {URL:"https://www.google.com"}
   delay 1.5
   make new document with properties {URL:"https://www.apple.com"}
   delay 2.5
   set index of window 2 to 1
   make new document
   close front window
end tell

-Chris

ugh. Thanks. Guess I’ll have to do the mouse click dance, available in KM but not in a script.

Hey Mitchell,

You can of course script Keyboard Maestro to click where you want with a do script command from the Keyboard Maestro Engine.

If you want some more scriptable options there's a spiffy Unix command-line tool:

https://www.bluem.net/en/mac/cliclick/

-Chris