Friday, September 9, 2011

Using ZeroClipboard with GWT

I have used ZeroClipboard in bug4j to copy stack traces to the clipboard.
It took me quite a while to make this work so I thought I should share the technique.

The most important thing to understand is that you do not tell ZeroClipboard to put text in the clipboard.
The way it works is that ZeroClipboard puts an invisible region over a widget that acts as a button and it is when that region is clicked that it copies to the clipboard the text you have defined.

Step 1: Include and initialize ZeroClipboard in your html page. In bug4j the static assets are stored in the /static/ directory, this is why initZeroClipboard() is necessary. If you store ZeroClipboard.js and ZeroClipboard.swf in / then that step is not necessary.
    <script type="text/javascript" language="javascript" src="user/user.nocache.js"></script>
    <script type="text/javascript" src="static/ZeroClipboard.js"></script>
    <script type="text/javascript">
        function initZeroClipboard() {
<body onload="initZeroClipboard();">

Step 2: Create an anchor that you link to ZeroClipboard and define the text to be copied to the clipboard.
        final Anchor copy = new Anchor("Copy");
        glueCopy("Hello World");
    public static native void glueCopy(String text) /*-{
        var clip = new $wnd.ZeroClipboard.Client();

And here is the result. As you can see, there is a "Copy" anchor at the bottom. When clicked, it copies the stack trace to the clipboard.


  1. I've done the same without success... I call it from a PopupMenu/MenuItem. The javascript method (here glueCopy) is called, but nothing is copied.

    I hide the popup after the javascript call.

    Any idea ?


  2. Well, looking at sample code, I do not understand exactly where the glueCopy("Hello world!"); is positionned ; in a ClickHandler added to the anchor, or anywhere else ?


  3. The glueCopy() creates a transparent window and moves it over an existing element. When the user clicks the element he actually clicks that transparent window which copies the text to the clipboard.

    The glueCopy() DOES NOT by itself copy text to the clipboard. You do not call that method from a "Copy" menu item or from a ClickHandler.

    You must call that method only if the element is already attached, rendered and has a position and size.
    You also have to make sure that the ZeroClipboard window stays over your element when the window is resized. If the element moves because of a re-layout then you must re-position the "clip".

    You can see how I use it here:

  4. So is it not required to call from any of the handler. But now i amd getting following error

    00:25:41.718 [ERROR] Failed to load module 'test' from user agent 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; BTRS100151; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET4.0C)' at localhost:4104

  5. In IE error is 'Object expected' and in FF error is '$wnd.ZeroClipboard.Client is not a constructor'