cocoaapplescriptapplescript-objcnspasteboard

How can I read the clipboard using AppleScriptObjC and NSPasteboard


I'm finding my way around AppleScriptObjC and have found Shane Stanley's Everyday AppleScriptObjC helpful. But I'm still having a hard time knowing where to start with NSPasteboard.

Here's what I have so far:

use AppleScript version "2.4"
use framework "Foundation"
use framework "AppKit"
use scripting additions

on readClipboard(theClipboard)
    set theClipboard to current application's NSPasteboard
    return theClipboard as text
end readClipboard

set theContents to missing value
its readClipboard(theContents)

Of course this doesn't work. But it does seem to be doing something.

It returns:

error "Can’t make «class ocid» id «data optr000000002852F974FF7F0000» into type text." number -1700 from «class ocid» id «data optr000000002852F974FF7F0000» to text

Any pointers would be greatly appreciated.


Solution

  • The NSPasteboard is a container which is able to hold many different items of different kinds. There are a few standard pasteboards defined like NSGeneralPboard, NSRulerPboard or NSDragPboard. For copy and paste actions the general pasteboard is used.
    The item stored inside the general pasteboard may differ also. It's possible to store public.rtf, public.jpeg etc. inside a pasteboard.

    Putting it all together we get this solution:

        set theClipboard to current application's NSPasteboard's generalPasteboard's stringForType:(current application's NSPasteboardTypeString)
    

    Have fun, Michael / Hamburg