Copy text to clipboard from bookmarklet

Ani picture Ani · Feb 18, 2011 · Viewed 13.8k times · Source

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 alerting 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.

Answer

Gundark picture Gundark · Oct 6, 2017

There is a nice little bookmarket in Github Gist that does the core of what you want -- copying to the clipboard. It does not use any external libraries, which I think of as an advantage.

As written, it copies some static text, but toward the bottom it talks about adapting it to other uses, such as copying the page title.

Since you've stated that 'The extraction is easy enough ...', you should be easily be able to adapt that gist to what you want to do.

I tried the plain vanilla version of the bookmarklet, because I have some static text that I often need to transfer to my clipboard. It works very well in Chrome 61 with no modifications. But make sure you read the comments; some people have suggestions on getting it to work in other browsers and scenarios.

Here is the code that I tested, already minified and ready to turn into a bookmarklet:

javascript:!function(a){var b=document.createElement("textarea"),c=document.getSelection();b.textContent=a,document.body.appendChild(b),c.removeAllRanges(),b.select(),document.execCommand("copy"),c.removeAllRanges(),document.body.removeChild(b)}("Text To Copy");

Gist has the pre-minified code as well.