Recently I have been wrestling with writing some code that will manipulate text on a user’s clipboard in a web browser. I thought I would share my findings here for others who might be interested in the same topic.
First lets start by looking at the Windows Clipboard in general. The clipboard, as we all know, stores blobs that the user has copied or cut from windows applications for future use. It stores this data in a variety of formats (if writing a windows application you can use the formats specified by the DataFormats class.) It is a convenient way to transport data between applications in windows. A simple example of writing to the clipboard in c# would then look like:
// For this example, the data to be placed on the clipboard is a simple // string. string textData = "I want to put this string on the clipboard."; // After this call, the data (string) is placed on the clipboard and tagged // with a data format of "Text". Clipboard.SetData(DataFormats.Text, (Object)textData);
Doing this on in a windows app is great, and easy, because that is really what the api’s were designed for… but what if we want to do this in a web app? Why would we do this you ask, well one argument is that as web apps and client apps converge, users are starting to expect more and more of the familiar windows UI concepts to be available to them on the web. Yeah, we’ll say that is the reason.
This copies the user’s selection to the clipboard.
Furthermore, you may only copy text that the user has selected in the browser.
The IE only alternative
An option, if for some strange reason you would like to build an application that only works in IE, is to take advantage of the clipboardData object. Using this, you can write and read directly from the clipboard and the user prompt is ignored when using the default security settings. Using this you can only take advantage of two ‘types’ on the clipboard: ‘text’ and ‘url’
To write text to the clipboard, you could then do the following:
var textToCopy = "This is some text for the clipboard"; window.clipboardData.setData("Text", textToCopy);
One nice thing about this, is that you can write arbitrary text to the clipboard (no user selection needed). But remember, this is Internet Explorer only. Mozilla does have a solution, but it is FF only. So if you want to use the clipboard in all browsers and not change security settings what can we do?
I looked and looked, and to the best of my knowledge Silverlight does not yet expose a method for accessing the clipboard. Alas.
So where does that leave us?
- If you want cross browser clipboard access you will need to use flash.
- If you do not want a dependency on flash, then you only have a good solution for IE
One last thing…