Auto Typer onto Unfocused Application How do I execute commands such as typing out text, onto an unfocused application in the background?

For example, I want to have it type out text in a messaging application while I'm on my browser.

tell application "System Events"
    activate
    delay 4
    repeat y times
        keystroke x
        delay z
        keystroke return

    end repeat


This is a section of the code I'm using, with x, y and z being message typed, times repeated and delay in between respectively. It works well when the window I want it to type in is in front, but how would I change it to allow me to designate the typing to a certain application?

Thanks in advance for any help.
System Events can only send a keystroke to the front most application or its window.

However, if you want to send a text message to a Buddy using Messages, while it's in the background, the following example AppleScript code works for me:

set targetBuddy to "+nnnnnnnnnnn"
set textMessage to "Hello World!"

tell application "Messages"
    set targetService to id of 1st service whose service type = iMessage
    set theBuddy to buddy targetBuddy of service id targetService
    send textMessage to theBuddy
end tell



The "+nnnnnnnnnnn" in set targetBuddy to represents the Buddy's phone number. Also, as coded, Messages is already opened and in the background. Otherwise additional code is required.




Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors.