Copy plain text in clipboard can be obtained using code shown below.
Components.classes["@mozilla.org/widget/clipboardhelper;1"]
.getService(Components.interfaces.nsIClipboardHelper)
.copyString("<font color=’#FF0000′>Hello world</font>");
Using this approach you can easily copy HTML text but… it remains plain text!
So if you copy the string <font color=’#FF0000′>Hello world</font> inside OpenOffice Calc (or Microsoft Word) you don’t see the text “Hello world” in red but the plain HTML tag.
Copy data (not necessary text) using a specific format requires nsITransferable‘s use.
You specify the mime type and if destination application (where you paste the data) is able to understand the format the correct result appears.
The code below insert real HTML data into clipboard and when you paste for example in OpenOffice you see the colored text.
var textHtml = "<font color='#FF0000'>Hello world</font>";
var xferable = Components.classes["@mozilla.org/widget/transferable;1"]
.createInstance(Components.interfaces.nsITransferable);
xferable.addDataFlavor("text/html");
var htmlstring = Components.classes["@mozilla.org/supports-string;1"]
.createInstance(Components.interfaces.nsISupportsString);
htmlstring.data = textHtml;
xferable.setTransferData("text/html", htmlstring, textHtml.length * 2);
var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
.getService(Components.interfaces.nsIClipboard);
clipboard.setData(xferable, null,
Components.interfaces.nsIClipboard.kGlobalClipboard);
Consider you want be able to choose if text must be pasted like HTML or plain text, for example because some application can’t handle stylished code.
Consider a plain text editor, it handles text not colorful HTML so you need the ability to paste based on destination application.
It’s easy! You only need to add a new flavor to the code shown above
var plainText = "Hello world in plain";
xferable.addDataFlavor("text/unicode");
var unicodestring = Components.classes["@mozilla.org/supports-string;1"]
.createInstance(Components.interfaces.nsISupportsString);
unicodestring.data = plainText;
xferable.setTransferData("text/unicode", unicodestring, plainText.length * 2);
Now text editors receive the string “Hello world in plain” without any formatting and rich editors receive a colored “Hello world”.
Rich editors like OpenOffice Calc or Writer allow user to choose how to paste using the “Paste special” function.
You can choose to paste the same data in different format or different data per different format.
Table2Clipboard uses two flavors, you can take a look at its source code here.