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.
<html>
<head>
    ...
    <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() {
            ZeroClipboard.setMoviePath('static/ZeroClipboard.swf');
        }
    </script>
</head>
<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");
        copy.getElement().setId("copyId");
...
        glueCopy("Hello World");
...
    public static native void glueCopy(String text) /*-{
        var clip = new $wnd.ZeroClipboard.Client();
        clip.setText(text);
        clip.glue('copyId');
    }-*/;




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.