patternModerate
Script to enter text in a box
Viewed 0 times
scripttextenterbox
Problem
Here's a little script that enters text into a document when activated.
I stuck the
tell application "TextEdit"
activate
end tell
delay 0.2
tell application "System Events"
keystroke "Hello World!"
keystroke return
end tellI stuck the
delay in there because otherwise the first few keystrokes tend to trigger before the window is done activating, so I end up with "lo World!" in the document and "Hel" in whatever other window had focus when the script was activated. Is that the proper use of delay, or is there a better way to circumvent that problem?Solution
Rather than using System Events to generate keystrokes, consider using TextEdit itself to insert text.
There is a difference, though: this version always appends "Hello World!" to the end of the document, rather than wherever the cursor happens to be. (Unfortunately, TextEdit's AppleScript dictionary mentions nothing about cursors.)
A side benefit of this approach is that you don't have to grant permission to use Assistive Access to your script.
tell application "TextEdit"
activate
tell first document to set its text to its text & "Hello World!\n"
end tellThere is a difference, though: this version always appends "Hello World!" to the end of the document, rather than wherever the cursor happens to be. (Unfortunately, TextEdit's AppleScript dictionary mentions nothing about cursors.)
A side benefit of this approach is that you don't have to grant permission to use Assistive Access to your script.
Code Snippets
tell application "TextEdit"
activate
tell first document to set its text to its text & "Hello World!\n"
end tellContext
StackExchange Code Review Q#73995, answer score: 11
Revisions (0)
No revisions yet.