Storing text in the clipboard using Silverlight 2

To provide users the ability to copy permalinks or store other useful information in the clipboard, there aren’t many options for web developers today.  There’s no APIs inside JavaScript to access the clipboard.  Here’s a solution that will at least enable this from your Silverlight 2 app for most of your users.

Internet Explorer-only Clipboard Access

IE provides limited clipboard support in script. Using the interoperability features in Silverlight this data can be accessed.  The user will be prompted to approve the clipboard access using this method.

Open IE Clipboard demo (133k)
Requires Silverlight 2 Beta 1

Here’s the static clipboard method I created to attempt to write to the clipboard.  If the user denies the request, or the clipboard API is not available, an alert informs the user.  A successful write to the clipboard does not result in any visual confirmation.

Clipboard.cs:

using System;
using System.Windows.Browser;

namespace ClipboardDemo
{
    public static class Clipboard
    {
        const string HostNoClipboard = "The clipboard isn't available in the current host.";
        const string ClipboardFailure = "The text couldn't be copied into the clipboard.";

        /// <summary>
        /// Write to the clipboard (Internet Explorer-only)
        /// </summary>
        public static void SetText(string text)
        {
            // document.window.clipboardData.setData(format, data);
            var clipboardData = (ScriptObject)HtmlPage.Window.GetProperty("clipboardData");
            if (clipboardData != null) {
                bool success = (bool)clipboardData.Invoke("setData", "text", text);
                if (!success) {
                    HtmlPage.Window.Alert(ClipboardFailure);
                }
            }
            else {
                HtmlPage.Window.Alert(HostNoClipboard);
            }
        }

    }
}

In the button event handler in my demo app, I simply call the static method to write to the clipboard:

        private void Go_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.SetText(ClipboardText.Text);
        }

Cross-browser, cross-platform solution

Now, this one’s a little interesting: since Flash does have clipboard access, you can actually use it from the web browser (JavaScript) or even Silverlight 2 (HTML DOM bridge) to enable a cross-browser, cross-platform clipboard copy function.  It’s a hack, but does get the job done.

I think there’s enough space in the world’s hard drives for both Flash and Silverlight on every computer!

Open Cross-browser, Cross-platform Clipboard demo (133k)

Requires Silverlight 2 Beta 1

To do this, I’ll be using the Flash component that ships with the syntaxhighlighter tool created by Alex Gorbatchev.  By simply adding a new Flash embed to the page and referencing his clipboard.swf Flash movie file, the Flash API will then attempt to write the proper data into the clipboard.

The implementation I’ve done here isn’t super robust: if the user doesn’t have Flash, there’s no error message for instance.  If the user’s browser is Internet Explorer, or implements the clipboardData API, then the Flash workaround will not be used.

Here’s the expanded Clipboard.cs.  Do note, I’m hard-coding the clipboard.swf location, so make sure you’re using a valid path on your server.

Clipboard.swf:

Make sure to download this file (here syntaxhighlighter) and store it in the same directory as your application.

Clipboard.cs:

using System;
using System.Windows.Browser;

namespace ClipboardDemo
{
    public static class Clipboard
    {
        const string HostNoClipboard = "The clipboard isn't available in the current host.";
        const string ClipboardFailure = "The text couldn't be copied into the clipboard.";
        const string BeforeFlashCopy = "The text will now attempt to be copied...";
        const string FlashMimeType = "application/x-shockwave-flash";

        // HARD-CODED!
        const string ClipboardFlashMovie = "clipboard.swf";

        /// <summary>
        /// Write to the clipboard (IE and/or Flash)
        /// </summary>
        public static void SetText(string text)
        {
            // document.window.clipboardData.setData(format, data);
            var clipboardData = (ScriptObject)HtmlPage.Window.GetProperty("clipboardData");
            if (clipboardData != null) {
                bool success = (bool)clipboardData.Invoke("setData", "text", text);
                if (!success) {
                    HtmlPage.Window.Alert(ClipboardFailure);
                }
            }
            else {
                HtmlPage.Window.Alert(BeforeFlashCopy);

                // Append a Flash embed element with the data encoded
                string safeText = HttpUtility.UrlEncode(text);
                var elem = HtmlPage.Document.CreateElement("div");
                HtmlPage.Document.Body.AppendChild(elem);
                elem.SetProperty("innerHTML", "<embed src=\"" +
                    ClipboardFlashMovie + "\" " +
                    "FlashVars=\"clipboard=" + safeText + "\" width=\"0\" " +
                    "height=\"0\" type=\"" + FlashMimeType + "\"></embed>");
            }
        }

    }
}

Hope this helps!

Comments

  1. May 22nd, 2008 | 5:04 am

    [...] Storing text in the clipboard using Silverlight 2 – Jeff Wilcox discusses how to provide users the ability to store information on the clipboard from your Silverlight application. There is not such API inside JavaScript, but now Silverlight enables you to do this. However there are some limitations in the available solutions which Jeff pointed out in his article so you can go and read about. [...]

  2. Tom
    May 23rd, 2008 | 6:45 am

    Oh, I love it! Thanks Jeff, this is some nice work. I don’t know if I agree with the direction of your fallback, but to each his own. :) I actually really wanted this functionality for one of my first real Silverlight apps, and now I’ve got a way. (Can you believe it? Some users can click a button no problem but have a terrible time understanding how to select a big block of text and hit Ctrl+C!)

    I have to admit though, it now seems more silly than ever that Silverlight doesn’t have a method to set the clipboard like Flash does. If it’s just too risky for you and you simply MUST have that enforced user interaction, how about providing a built-in control that the user can click on, with a property and/or event supplying the text to be copied to the clipboard? It could be a helpful compromise.

  3. May 27th, 2008 | 9:37 am

    Tom, I totally hear you. I hope we find a way to add clipboard support into the platform at some point. This is good to hear…

    This is less an awesome solution, more about the flexibility of the HTML DOM interop features in Silverlight (in my mind at least)… I’m biased, having worked on the interop features quite a bit!

    -Jeff

  4. Hai Son
    October 14th, 2008 | 7:05 pm

    How can to get the clipboard in FireFox?