Storing text in the clipboard using Silverlight 2

21 May 2008

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!

Jeff Wilcox is a Software Engineer at Microsoft in the Open Source Programs Office (OSPO), helping Microsoft engineers use, contribute to and release open source at scale.

comments powered by Disqus