Search code examples
hyperlinknumbersapplescript

Use Applescript to create hyperlink in a text item in Numbers


I'm unable to make a text item (an iWork container) a hyperlink. The equivalent actions to be performed with the GUI would be:

  • Add Text Container
  • Modify Text
  • Select Text Container, right click and select "add link"

I succeeded in using Applescript with Numbers to create a hyperlink in a cell value. To do this I set the cell value to the =hyperlink(url,text) function. However, I don't want to have to create a new table to insert a hyperlink.

I used Applescript Numbers Dictionary to find any reference to hyperlink for iWork containers but couldn't find any.


Solution

  • The solution that I found implies manipulating Numbers UI by sending keystrokes to the application to create the link.

    tell application "Numbers"
        set myDocument to open POSIX file "/path/to/my/doc.numbers"
        tell myDocument
            activate -- required in order to receive keystrokes in Numbers
            tell sheet 1
                set myText to make text item
                set object text of myText to "Hello World"
                tell application "System Events" to keystroke "a" using command down -- select all the text
                tell application "System Events" to keystroke "k" using command down -- add a link
                tell application "System Events" to keystroke "https://mylink" -- input the link
                tell application "System Events" to keystroke return using command down -- close the link dialog box
            end tell
        end tell
    end tell