AppleScript – How to Convert URL Type to String

applescript

In AppleScript, I can cast some variables (e.g., the clipboard), to the built-in URL type:

set theURL to the clipboard as URL

If my clipboard contains an RTF link to https://temochka.com/, theUrl will be assigned a raw value like this (which can be seen in the Script Editor replies window):

«data url 68747470733A2F2F74656D6F63686B612E636F6D»

This last part (68747470733A2F2F74656D6F63686B612E636F6D) is a hex-encoded string that can be decoded as "https://temochka.com". Is there a way to extract just this value? Or maybe get the full URL value out?

Best Answer

If set theURL to the clipboard as URL returns:

«data url 68747470733A2F2F74656D6F63686B612E636F6D»

Then if you are set on working with that class, you need to first write it to a temporary file and then read it back, as in the following example AppleScript code:

set tmpFilename to "/tmp/theURL.txt"

set theURL to the clipboard as URL

writeToFile(theURL, tmpFilename, true)

set theURL to read tmpFilename


on writeToFile(theData, theFile, overwriteExistingContent)
    try
        set theFile to theFile as string
        if theFile contains "/" then
            set theOpenedFile to open for access theFile with write permission
        else
            set theOpenedFile to open for access file theFile with write permission
        end if
        if overwriteExistingContent is true then set eof of theOpenedFile to 0
        write theData to theOpenedFile starting at eof
        close access theOpenedFile
        return true
    on error
        try
            close access file theFile
        end try
        return false
    end try
end writeToFile 

Notes:

The writeToFile(theText, theFile, overwriteExistingContent) handler is a slightly modified handler from Reading and Writing Files

The handler from the linked Apple support document was modified to handle both POSIX and HFS+ file paths.

When the clipboard returns what's show herein, it also can return https://temochka.com directly by using, e.g.:

set theURL to the clipboard as text

enter image description here