Snippets code from my daily experience

August 18, 2007

Put in clipboard same content in multiple formats using XUL.

Copy plain text in clipboard can be obtained using code shown below.



    .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[";1"]



var htmlstring = Components.classes[";1"]

    .createInstance(Components.interfaces.nsISupportsString); = textHtml;

xferable.setTransferData("text/html", htmlstring, textHtml.length * 2);

var clipboard = Components.classes[";1"]


clipboard.setData(xferable, null,


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";


var unicodestring = Components.classes[";1"]

    .createInstance(Components.interfaces.nsISupportsString); = 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.


Create a free website or blog at