Hi folks, I wrote an AppleScript to add attachments to a note in Notes.app at any arbitrary point in the body of the note. It works reliably in my testing so far. But it relies on GUI scripting like setting a window to a specific size and then clicking on specific coordinates. That seems brittle, and I’m worried about it breaking as its run on other machines.
Can you suggest ways to make the script more robust?
Here’s the code, and below that is an explanation and other things that I tried.
-- path to the file
set theFile to POSIX file "{full_path_to_file}"
-- name of the note to modify
set theNoteID to "{note_id}"
-- the string in the note where you want to place the cursor
set theString to "{placeholder_text}"
-- open the note and place the cursor
tell application "Notes"
activate
tell note id theNoteID
show
end tell
set bounds of front window to {{221, 68, 1961, 1118}}
end tell
-- Find the placeholder text and leave it in a state where it's highlighted/selected and in focus.
tell application "System Events"
tell process "Notes"
set frontmost to true
delay 1 -- Wait for Notes to become active
keystroke "f" using {{command down}} -- Activate the find function
delay 1
keystroke theString -- find your specific text string
keystroke return
delay 1
click at {{1841, 128}} -- Click the Done button on the find toolbar to dismiss it
delay 1
end tell
end tell
-- copy the file to the clipboard
tell application "Finder"
set the clipboard to theFile
end tell
-- paste the file at the cursor location
tell application "System Events"
tell process "Notes"
keystroke "v" using {{command down}}
delay 1
end tell
end tell
The code is designed to be driven from Python, thus the “{}” around placeholders and the double-{} in certain spots.
Upstream of this script I have other code that assembles the HTML of the new note that I want to create. Wherever there are files or images in the HTML I convert them to placeholder text and keep track of the appropriate attachment, and then create the new note using a separate AppleScript.
Then this script runs and 1) uses command-F to find the placeholder text and highlight it, and 2) copy and paste the file or image on top of the placeholder. This results in the file or image appearing in the exact right place in the document with none of the artifacts mentioned in the post How can I attach a PDF to a note in Notes.app?, which I still personally experienced when trying that solution on Ventura 13.4.
It works reliably for me but it seems fragile. I tried addressing the “Done” button directly (the one that appears on the find toolbar), and can see info about it in Accessibility Inspector, but nothing I tried worked.
Any help is much appreciated!