Skip to content

Instantly share code, notes, and snippets.

@stefanmaric
Created September 7, 2016 20:54
Show Gist options
  • Save stefanmaric/2abf96c740191cda3bc7a8b0fc905a7d to your computer and use it in GitHub Desktop.
Save stefanmaric/2abf96c740191cda3bc7a8b0fc905a7d to your computer and use it in GitHub Desktop.
Create Bookmarklet (browser bookmark that executes Javsacript) to copy a given text to Clipboard

Copy-to-clipboard Bookmarklet

Create Bookmarklet (browser bookmark that executes Javsacript) to copy a given text to Clipboard.

This is the base javascript:

(function (text) {
  var node = document.createElement('textarea')
  var selection = document.getSelection()

  node.textContent = text
  document.body.appendChild(node)

  selection.removeAllRanges()
  node.select()
  document.execCommand('copy')

  selection.removeAllRanges()
  document.body.removeChild(node)
})('Text To Copy')

Minify it (you can use UglifyJS or any other) to get something like this:

!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");

Prefix it with javascript::

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");

Then add it as a new bookmark, in the URL field:

Chrome Example

More applications

You can do stuff like a "Copy page title" bookmarklet by simply passing document.title instead of the fixed string:

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)}(document.title);
@atjackiejohns
Copy link

The code works in Chrome but only when on an actual webpage. It's not working for empty chrome tabs or while viewing extensions (which is my personal use case).

This seems to work as well but the same problem:

javascript:(function(){
  var data = "Your data to be copied";
  var tempInput = document.createElement("input");
  tempInput.value = data;
  document.body.appendChild(tempInput);
  tempInput.select();
  document.execCommand("copy");
  document.body.removeChild(tempInput);
})();

@nicoleahmed
Copy link

nicoleahmed commented Sep 7, 2023

Hey atjackiejohns
I think what you're experiencing is the general exclusions that Google applies to Chrome - extensions and scripts aren't allowed on certain pages by Google - this includes the chrome special tabs, some aspects of the chrome store - and I think also on other extensions too, but I'm not certain on that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment