1

Is it possible to put a variable in the clipboard? I've seen a lot of posts that do this by selecting the text existing in a DOM element and then copying it which is fairly straightforward but I haven't seen one that copies something that isn't in the DOM.
I'd like to take a variable or a constant holding a string and send it to the clipboard without it ever appearing in the browser window (even as a hidden element). I know using a hidden element would be a fast solution to this but it feels a little hacky if there is a more concise way.

tfantina
  • 788
  • 11
  • 37
  • As far as I know you cant do it and I searched for quite some time. Everything I have seen involves creating a text area out of view seleting the text copying then destroying the element. – GifCo May 16 '19 at 15:41
  • see the comments here: https://stackoverflow.com/questions/48215841/copy-string-to-clipboard-without-using-a-dom-element – mistahenry May 16 '19 at 15:47

2 Answers2

7

You can use the clipboard API. it doesn't have full support yet but it's pretty good.

you can use it like so:

navigator.clipboard.writeText("hello from site!")
  .then(() => console.log(`wrote to clipboard!`))
  .catch((error) => console.error(error));

Notice that this works only if the current website is focused (the document is focused)

In order to read from the clipboard, you can use the following function:

navigator.clipboard.readText()
  .then(text => console.log(text))
  .catch((error) => console.error(error));

This one requires two things in order to work:

  • same as before, the user needs to be focused on the website
  • user will be prompted to confirm the site's ability to read from the clipboard (since it can contain sensitive data):

    enter image description here

Firefox

For Firefox, in addition to asking the user for permission to read the clipboard, it also only allows pasting it into a textarea:

Firefox supports the "clipboardRead" permission from version 54, but only supports pasting into elements in content editable mode, which for content scripts only works with a . For background scripts, any element can be set to content editable mode.

Thatkookooguy
  • 6,669
  • 1
  • 29
  • 54
  • 1
    Unfortunately, I'm developing this for a lot of corporate users on IE but I will check this as correct because technically this is exactly what I was looking for. – tfantina May 16 '19 at 16:44
3

You asked for Javascript rather than jquery, so here you go.

function toClip(text) {
    var copy = document.createElement("textarea");
    document.body.appendChild(copy);
    copy.value = text;
    copy.select();
    document.execCommand("copy");
    document.body.removeChild(copy);
}

While this doesn't use an existing element in the DOM, it creates one and immediately removes it.

This

shadow2020
  • 1,315
  • 1
  • 8
  • 30