Ani Ani - 2 months ago 24
Javascript Question

Copy text to clipboard from bookmarklet

I'm trying to write a little bookmarklet that can extract some text from the active page and load that into the clipboard.

The extraction is easy enough, but I'm really stuck doing the clipboard-copying part. Currently, I'm just

ing the text and hitting Ctrl+C to copy the text from the message-box, which isn't ideal.

I've read How to Copy to Clipboard in JavaScript and other questions that suggest I use zeroclipboard, but I have no idea how one would make that work from a bookmarklet, considering I have to load external flash and javascript resources to be able to use the library.

I have no issues with messing up the page's DOM to accomplish this or having to enable some permissions on my browser (Google Chrome), considering this is just a private bookmarklet.

Any pointers would be appreciated.


A couple disclaimers:

  1. I'm not trying to spam you
  2. I gain nothing if you choose to use this

I made a bookmarklet generator a while back to make it easier for me to create bookmarklets.

It's jQuery enabled, but that doesn't mean you have to use jQuery.

You can check out the source to see how to import another script/library into a page via a bookmarklet.

In particular, the lines that import jQuery:

if (!window.zbooks)
    //if zbooks hasn't been set, initialize it

    //s used for the Script element
    var s = document.createElement('script');
    //r used for the Ready state
    var r = false;
    //set the script to the latest version of jQuery
    s.setAttribute('src', '');
    //set the load/readystate events
    s.onload = s.onreadystatechange = function()
 * execute if the script hasn't been ready yet and:
 * - the ready state isn't set
 * - the ready state is complete
 *   - note: readyState == 'loaded' executes before the script gets called so
 *     we skip this event because it wouldn't have loaded the init event yet.
      if ( !r && (!this.readyState || this.readyState == 'complete' ) )
        //set the ready flag to true to keep the event from initializing again
        r = true;
        //prevent jQuery conflicts by placing jQuery in the zbooks object
        window.zbooks = {'jQuery':jQuery.noConflict()};
        //make a new zbook
        window.zbooks[n] = new zbooks(c);
    //append the jQuery script to the body

I hope that helps.