1

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.

  • You would need to use JavaScript for Automation (specifically, JSObjC) to send keystrokes to a specific, unfocussed application. – CJK May 16 at 22:20
1

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.

  • 1
    Worth noting that AppleScript cannot initiate a new conversation to a name or number that has not previously been messaged in the Messages app (or, of course, through an iDevice that syncs to Messages on macOS through iCloud), i.e. you can only iMessage someone you've iMessaged before. – CJK May 13 at 13:51
  • @CJK, Thanks for the comment, good information to know. Obviously the main point of the answer is the first sentence, the rest was thrown in so it wouldn't get flagged with: "We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed." 😁 – user3439894 May 13 at 14:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .