Apple Script : How can I copy html content to the clipboard?

I've found a solution and the idea is to use the HTML class directly instead of the RTF class. (TextEdit or web editors can handle this HTML class as well as the RTF class data)
All you have to do is to convert your html code into raw hexcode.
The complete code looks like:

hex=`echo -n "your html code here" | hexdump -ve '1/1 "%.2x"'`
osascript -e "set the clipboard to «data HTML${hex}»"

You can combine them into one sentence, of course.
Hope this helped anybody interested. :)


I'm not super great at AppleScript, but here's something that works. Unfortunately, since it opens a Safari window, it's not instant. You may need to adjust the delay value to compensate for slower performance, but 0.25 s seemed long enough in my tests.

set theHTML to "<b>bold text</b>"

tell application "Safari"
    open location "data:text/html," & theHTML
    activate
    tell application "System Events"
        keystroke "a" using {command down}
        keystroke "c" using {command down}
    end tell
    delay 0.25
    close the first window
end tell

After that, the rendered text should be on your clipboard, ready to paste into TextEdit.


The solution by @k-j would not work if the input HTML is too big, you might encounter some error messages like below:

/usr/bin/osascript: Argument list too long

I made some improvements to @k-j's solution by converting it to an executable and handling data via pipe. I hope it helps as well.

Executable

~/bin/pbcopyhtml:

#!/bin/sh
printf "set the clipboard to «data HTML$(cat $@ | hexdump -ve '1/1 "%.2x"')»" | osascript -

Usage

from pipe

$ printf '# title\n\n- list\n- list' | cmark | ~/bin/pbcopyhtml
$ osascript -e 'the clipboard as record'
«class HTML»:«data HTML3C68313E7469746C653C2F68313E0A3C756C3E0A3C6C693E6C6973743C2F6C693E0A3C6C693E6C6973743C2F6C693E0A3C2F756C3E0A»

from file

$ printf '# title\n\n- list\n- list' | cmark > sample.html
$ ~/bin/pbcopyhtml sample.html
$ osascript -e 'the clipboard as record'
«class HTML»:«data HTML3C68313E7469746C653C2F68313E0A3C756C3E0A3C6C693E6C6973743C2F6C693E0A3C6C693E6C6973743C2F6C693E0A3C2F756C3E0A»