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);
@keemor
Copy link

keemor commented Jan 10, 2017

Works in Chrome, but Firefox 50.1 says:
document.execCommand('cut'/'copy') was denied because it was not called from inside a short running user-generated event handler.

@mems
Copy link

mems commented Mar 11, 2017

Instead of create a temporary element (and erase current user's selection), use directly the copy event:

let copyListener = event => {
	document.removeEventListener("copy", copyListener, true);
	event.preventDefault();
	let clipboardData = event.clipboardData;
	clipboardData.clearData();
	clipboardData.setData("text/plain", "Hello, world!");
	clipboardData.setData("text/html", "<b>Hello, world!</b>");
};
document.addEventListener("copy", copyListener, true);
document.execCommand("copy");

@lettucehead
Copy link

This rocks!!

@Luiz-N
Copy link

Luiz-N commented Sep 7, 2017

Thanks for this clever hack! Just to add that I needed to add semicolons after each statement to get it working in chrome

@Gundark
Copy link

Gundark commented Oct 6, 2017

Very useful, thanks very much. I've referenced this in answer to relevant questions on Stack Overflow. :-)

@brry
Copy link

brry commented Oct 7, 2017

Works in IE 11.0.96, but not in firefox 55.0.2 or 56.0 (tested on two computers). It seems like nothing happens, the old clipboard is still there. If I open the bookmarklet in a new tab, it displays "true". Any idea what to change?

@HiThere321
Copy link

Here is a shorter stringified version with the text to copy in front to make it easier to spot in the bookmark manager. Just replace TXT with whatever you want to copy.
javascript:{t='TXT';d=document;d.body.appendChild(Object.assign(d.createElement('textarea'),{value:t})).select();d.execCommand('copy');}

Here's a variation with a pop-up alert displaying what was copied. I prefer this one, but if you had something sensitive in there like a password then you might want to use the one above or change the alert at the end to not display the input (remove the +t at the end).

javascript:{t='TXT';d=document;d.body.appendChild(Object.assign(d.createElement('textarea'),{value:t})).select();d.execCommand('copy');alert('Text Copied\n'+t);}

I've found it very useful and have a bunch of bookmarklets in a folder in my bookmark bar for different usernames and such. You can use either single or double quotes for strings in JS so if your text contained one you could enclose it in the other (eg. t="Joe's final words"+' were "good bye".') You could even experiment with setting t to a JS function to copy the current date or something queried from the current page you are on. Lots of possibilities!

@cipher0x30
Copy link

Seems late to the party, but hope this could still help with the Firefox issue.
javascript:{t="text";d=document;d.body.appendChild(Object.assign(d.createElement('textarea'),{value:t})).select();d.execCommand('copy');d.body.lastElementChild.setAttribute("hidden","hidden");d.preventDefault;}
The above code prevents showing "true" when clicked and hides the element that is created.

@brry
Copy link

brry commented Feb 18, 2021

@cipher0x30: thank you so very much!!! This worked perfectly for me - until I renamed the bookmark. Now I can't get it to work again...

@cipher0x30
Copy link

@cipher0x30: thank you so very much!!! This worked perfectly for me - until I renamed the bookmark. Now I can't get it to work again...

I also experienced that, but I found a little trick when it happens, although it also needs a few clicks.

Before trying to copy-paste, open developer console or inspect element and then click the bookmarklet (copy-paste).

Worked for me, hope it works for you as well.

@brry
Copy link

brry commented Feb 18, 2021

Upon creating the bookmark, it only works once for me. Subsequent clicks show the following message in the console:
document.execCommand('cut'/'copy') wurde abgelehnt, weil es nicht von innerhalb einer kurz dauernden benutzergenerierten Ereignisbehandlung aufgerufen wurde.
There might be solutions down the rabbit hole here: https://stackoverflow.com/q/41094318.
All I want is an easy way to copy my rather long emailadress to the clipboard, preferably with a single click on a bookmark...

@kylesnowschwartz
Copy link

kylesnowschwartz commented Jun 22, 2021

Instead of create a temporary element (and erase current user's selection), use directly the copy event:

let copyListener = event => {
	document.removeEventListener("copy", copyListener, true);
	event.preventDefault();
	let clipboardData = event.clipboardData;
	clipboardData.clearData();
	clipboardData.setData("text/plain", "Hello, world!");
	clipboardData.setData("text/html", "<b>Hello, world!</b>");
};
document.addEventListener("copy", copyListener, true);
document.execCommand("copy");

This works really well, except when I use it twice I get the following console error:
Uncaught SyntaxError: Identifier 'copyListener' has already been declared

What do you think is causing this?

Solved: Change let copyListener = to var copyListener =. Let variables cannot be redeclared!

@brry
Copy link

brry commented Jun 22, 2021

Thanks you so much, @kylesnowschwartz! This is the final version that works for me:

javascript:
var copyListener = event => {
	document.removeEventListener("copy", copyListener, true);
	event.preventDefault();
	let clipboardData = event.clipboardData;
	clipboardData.clearData();
	clipboardData.setData("text/plain", "TEXTIWANTTOCOPYTOCLIPBOARD");
};
document.addEventListener("copy", copyListener, true);
document.execCommand("copy");
document.body.lastElementChild.setAttribute("hidden","hidden");
document.preventDefault;

@PopularAbbyeet
Copy link

none of this is working. How do I make it work on Chromebook?

@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