JavaScript copy to clipboard

From Trephine

Jump to: navigation, search
« Browser clipboard access JavaScript Excel data extractor idea »

[subscribe] Recent blog entries

Live Demos

JavaScript copy to clipboard

This article demonstrates how to insert text into the system clipboard using trephine and a little custom JavaScript.

Just like the previous article about browser clipboard access and all of the demos, the following code depends on trephine, which provides a JavaScript API for executing privileged code inside a Rhino context running in a Java applet.

Getting right down to it, here's the executable demo:

// Setup steps to perform once trephine has loaded
var setup = function(){
  window.clipboard = {
    write: function(text) {
      var result = trephine.js( function(text) {
        var dt = java.awt.datatransfer;
        var trans = new dt.Transferable({
          getTransferDataFlavors: function() {
            var a = java.lang.reflect.Array.newInstance(dt.DataFlavor, 1);
            a[0] = dt.DataFlavor.plainTextFlavor;
            return a;
          },
          isDataFlavorSupported: function(flavor) {
            return dt.DataFlavor.plainTextFlavor.equals(flavor);
          },
          getTransferData: function(flavor) {
            return text.toString();
          }
        });
        java.awt.Toolkit.defaultToolkit.systemClipboard.setContents(trans, null);
        return true;
      }, text );
      if (result.error) throw result.error;
      return ( result.result ? result.result.toString() + '' : '' );
    }
  };
  alert('Setup complete! Now scroll down and try it out.');
};
 
// Load trephine, ask for privileges, then call setup()
trephine.load({
  onload: function() {
    trephine.askPermission( function(response) {
      if (response) setup(); 
      else alert("Sorry, you must grant privileges to access the clipboard.");
    } );
  }
});
< execute this code >

When you click the execute button at right, this code will:

  1. Load trephine and prompt for elevated permissions,
  2. Create a clipboard object with a write() function for setting clipboard data.

When you pass text to window.clipboard.write(), it will attempt to write that data into the clipboard buffer, or throw an exception on failure.

To try it out, highlight some text on this page, then execute the following:

try {
  var text = (function(){
    if (window.getSelection) return window.getSelection();
    if (document.getSelection) return document.getSelection();
    if (document.selection) return document.selection.createRange().text;
    return null;
  })() + '' || "No text was selected, so this will have to do.";
  window.clipboard.write(text);
  alert('Clipboard text set to: ' + text);
} catch(err) {
  alert('Error setting text: ' + err.message);
}
< execute this code >

That's it!

How to use it in your code

Aside from the setup described above, you'll need to add trephine.js to your page as explained on the getting started page:

<script src="http://trephine.s3.amazonaws.com/trephine.js"></script>

If you don't want to include the <script> tag directly in the page, you can load it dynamically. Bespin trepanation has a good example of how to achieve this, using script onload piggybacking to automatically perform the setup steps after the script is loaded.

Explicit public domain declaration

Just so there's no confusion: all of the code snippets on this page are provided "AS IS", without warranty of any kind, express or implied.

All of the code snippets on this page are hereby released into the public domain by the me, the copyright holder. This applies worldwide. Or in case this is not legally possible: The copyright holder grants any entity the right to use this work for any purpose, without any conditions, unless such conditions are required by law.

If you'd feel better with a "real" license, you're free to use code snippets on this page under the MIT license as described on the about page.

Any links back to this site are always appreciated, but not required. Enjoy!

--Jim R. Wilson (jimbojw) 21:07, 25 March 2009 (UTC)
Personal tools