Using Frontmost Application?

I’m no fan of Automator, but I believe it’s the easiest way to install an AppleScript (and thereby a shell script or ruby script) as a service. Once it’s installed you don’t have to bother with Automator.

The keystroke command does not exist for applications. So I can assure you that it should be directed to System Events.

And the fact that someone once accidentally succeeded with delays is explained in a completely different way. Namely, the fact that AppleScript is famous for its “fool-proof” because it automatically redirects many erroneous commands to the right application. Of course, fixing a user error slows down the script, which creates some unpredictable delay, giving the impression of a “working” script.

In fact, the script itself should control the delay. Every time after opening a new window, menu or dialog. Using automated delay like this:

repeat until window 1 of process theProcess exists
delay 0.1
end repeat

Then you can send the keystroke to System Events, and it keystrokes to this new window.

I didn’t want to be clever here and continue the topic, but I always want users not to get lost in their work. Of course, this is my personal opinion: understanding how everything works is important for writing durable and stable scripts.

Best practice:

 
tell application "Safari" to activate
tell application "System Events"
    tell process "Safari"
        -- Perform user interface scripting tasks
    end tell
end tell

From Apple:

Mac Automation Scripting Guide: Automating the User Interface

https://developer.apple.com/library/archive/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/AutomatetheUserInterface.html#//apple_ref/doc/uid/TP40016239-CH69-SW1

User interface scripting terminology is found in the Processes Suite of the System Events scripting dictionary. This suite includes terminology for interacting with most types of user interface elements, including windows, buttons, checkboxes, menus, radio buttons, text fields, and more. In System Events, the process class represents a running app. Listing 37-1 shows how to target an app using this class.

Listing 37-1
AppleScript: Targeting an app for user interface scripting

 
tell application "System Events"
    tell process "Safari"
        -- Perform user interface scripting tasks
    end tell
end tell

So what? I have already seen this documentation. So we read the same thing but understand it differently. The examples in the documentation are for UI element commands (for example, click) and have no connection with the keystroke and key code commands of the System Events application.

I don’t want to explain it any more.

Keystrokes in the System Events application pertain 100% to the UI. When pasting using System Events, it’s focus is the application that has the attention. It’s completely relevant.