In a script, I need to put rich text from the pasteboard into TextEdit. This works as expected in AppleScript:
tell application "TextEdit"
activate
set myrtf to the clipboard as «class RTF »
set mydoc to make new document
set text of mydoc to myrtf
end tell
However, I need to use JXA, and I can’t figure out how to translate the above AppleScript to that.
One (solved) issue is that in JXA, you can read any pasteboard content other than plain text only using the JXA-Objective-C bridge. But from then on, I’m stuck. Either I end up with plain text containing the raw RTF attributed string ("{\\rtf1\\ansi\\ansicpg1252\\cocoartf1671\\cocoasubrtf600\n{\\fonttbl
…) or I get a conversion error (-10000). Here is what I tried:
var TextEdit = Application('TextEdit');
TextEdit.includeStandardAdditions = true;
TextEdit.activate();
ObjC.import('AppKit');
var content = $.NSPasteboard.generalPasteboard.stringForType('public.rtf');
var data = content.dataUsingEncoding('NSUTF8StringEncoding');
var string = $.NSAttributedString.alloc.initWithRTFDocumentAttributes(data, '0');
var mydoc = TextEdit.Document().make();
mydoc.text = content.js; // or data.js or string.js
If I use content.js
in the last line, I get the raw RTF attributed string mentioned above, if I use data.js
or string.js
instead, I get Error -10000.
It must be possible to translate the simple AppleScript above to JXA. Where is my mistake?