Copying text and HTML to the clipboard at the same time from a Firefox add-on

The JavaScript code below demonstrates how to copy two different formats of data to the clipboard at the same time. So applications wanting only text can grab the text version, but applications supporting HTML can grab that version instead. The basic idea is that you call addDataFlavor() for each type of data you want to represent on the clipboard, then call setTransferData() for each of those flavors of data.

function CopyToClipboard(textData,htmlData){
	var text      = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
	text.data     = textData;
	var html      = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
	html.data     = htmlData;
	var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
	trans.addDataFlavor("text/html");
	trans.addDataFlavor("text/unicode");
	trans.setTransferData("text/html", html, htmlData.length);	
	trans.setTransferData("text/unicode", text, textData.length*2);	
	var clipid = Components.interfaces.nsIClipboard;
	var clip   = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
	clip.setData(trans, null, clipid.kGlobalClipboard);
}

Leave a Reply