Get text from current cursor position From Pages app in Mac

Viewed 737

Is it possible to get the text of Pages app, from its current cursor position? My requirement is like, when user type something in "Pages", I have to show suggestions for the word they are typing.

so I want to find out the current or last word, near current cursor position from "Pages" app. Either by using AppleScript or Accessibility? Text is not selected. I am not looking for "Services" also. For apps other than "Pages", I used Accessibility and appleScript. but for pages I am not finding any way.

I have also tried below AppleScript, but some reason it works perfectly in "Script Editor", but when I use it in my code, it goes to infinite loop.

tell application "Pages"
    activate
end tell
tell application "System Events"
    tell application "System Events"
        key code 123 using {shift down, command down} -- shift-command-left
    end tell
    tell process "Pages"
        keystroke "c" using {command down}
        delay 1
        tell application "System Events"
            key code 124 -- shift-command-left
        end tell
        set myData to (the clipboard) as text
        return myData
    end tell
end tell

If I run this AppleScript in my app, it freeze my Mac only, I have to force quit the Mac to stop it.

1 Answers

This works for me using the latest versions of macOS Mojave and Pages

property theApp : "Pages" -- change value to name of any other application (TextEdit)

tell application theApp to activate
delay 3
tell application "System Events"
    tell application process theApp
        -- Move the insertion point to the beginning of the previous word.
        key code 123 using {option down} -- left arrow key while holding option down
        delay 0.2
        -- Move the insertion point to the end of the next word. (selects the word)
        key code 124 using {shift down, option down} -- right arrow key while holding option and shift down
        delay 0.2
        keystroke "c" using {command down} -- copies selected wprd 
        delay 0.2
        -- Next 2 key code commands attempt to restore cursor location  
        key code 124 using {option down} -- right arrow key while holding option down
        delay 0.2
        key code 123 using {option down} -- left arrow key while holding option down
        tell current application to set myData to (the clipboard) as text
        delay 4
        return myData
    end tell
end tell
Related