Keystroke to background app - AS vs. Automator

First off, if any of you know me, I’m not a fan of UI scripting, but I recognize there are valid use cases (as a last resort, when all else has failed and hell has frozen over :wink: )

One thing that comes up is sending keystrokes to non-frontmost applications. I know historically this has been a no-no in AppleScript - keystrokes always go to the frontmost app, which leads to shenanigans around context switching, etc., e.g.

tell application "Safari" to activate
tell application "System Events"
	keystroke "a"
end tell

which gets into a whole mess of restoring the previous frontmost app, etc.

However, If you use Automator’s Watch Me Do action to record keystrokes, it includes an application target:

This target is tracked and honored, such that on playback, keystrokes go to the target application, ignoring the frontmost application, and avoiding the context switch of activating/restoring the target app.
In fact, this is so ingrained I can’t see any way to change it to a different app (or even frontmost), even if I wanted to.

So my question is this:

Was this level of application targeting added to AppleScript, and I’m just not aware of it?
Is Automator doing all the work under the hood?
Why can’t we do this in AppleScript? [rhetorical question :wink: ]

It looks like Watch Me Do uses a private UIRecording framework, which seems to hide most everything about itself. Since the user-facing event script doesn’t have the target in it, it must get the context from elsewhere, such as the workflow document. That has a tantalizing entry for userEvents, but it is also obfuscated pretty well, so I think “under the hood” or “behind the scenes” definitely covers it.

The action is surprisingly useful for getting UI object references, though.

If you have a reference to the property of any
UI element of any application.
You can just tell system events
then Perform the click action on the UIElement property reference
Or set its focus to true.
Then click at point x,y