Hovhannes Gevorgyan
Hovhannes Gevorgyan

Reputation: 552

Copy the text to the Clipboard without using any input

I just saw many articles in the web to find a solution to copy text to the Clipboard. But Every tutorials explain with inputs examples.

  function GeeksForGeeks() {
            var copyGfGText = document.getElementById("GfGInput");
            copyGfGText.select();

            document.execCommand("copy");

            alert("Copied the text: " + copyGfGText.value);
          }
  <input type="text" value="GeeksForGeeks" id="GfGInput">

         <!-- The button used to copy the text -->
         <button onclick="GeeksForGeeks()">Copy text</button>

But I need to copy just a simple text. Is there a way to copy simple string from variable to the Clipboard? example`

let text = "copy this text to the clipboard";

Upvotes: 8

Views: 20242

Answers (5)

Avinash
Avinash

Reputation: 146

Try the exact same thing with the input field with opacity:0; position absolute; z-index:-1;. This basically makes the field invisible to user and visible to browser. Same thing won't work for display: none. I've been using this in a lot of projects of mine without any reported issues.

Upvotes: 0

Hamid Raza
Hamid Raza

Reputation: 32

In Jquery:

var text = `Your Text`;
$('body').append(`<input class="temp-input" value="${text}">`);
$('.temp-input').select();
document.execCommand("copy");
$('.temp-input').remove();

Upvotes: 0

mw509
mw509

Reputation: 2093

You should be able to do this with document.createElement(); like this;

function CopyMe(TextToCopy) {
  var TempText = document.createElement("input");
  TempText.value = TextToCopy;
  document.body.appendChild(TempText);
  TempText.select();
  
  document.execCommand("copy");
  document.body.removeChild(TempText);
  
  alert("Copied the text: " + TempText.value);
}
<button onclick="CopyMe('The text here will be copied')">Copy text</button>

Let me know how this helps.

=============== UPDATE - March 2023 ===========

The execCommand method may not be available in all browsers so a better way to do this now would be;

function copyToClipboard(text) {
  navigator.clipboard.writeText(text)
.then(() => {
  console.log(`Copied text to clipboard: ${text}`);
  alert(`Copied text to clipboard: ${text}`);
})
.catch((error) => {
  console.error(`Could not copy text: ${error}`);
});
}
<button onclick="copyToClipboard('The text here will be copied')">Copy text</button>

This is a better and cleaner way to do same thing but if the website you're working on has a Content Security Policy (CSP) or other security settings that prevent access to the clipboard you will get errors (https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes).

Upvotes: 27

Matheus Sant Ana
Matheus Sant Ana

Reputation: 690

Using Sarah code with improvement, asked by Fluchaa:

$("#myButton").click(function() {
    this.focus();
    navigator.clipboard.writeText("MY PLAIN TEXT")
                                   .then(() => { alert("Copy successful"); })
                                   .catch((error) => { alert(`Copy failed! ${error}`); });
});

Upvotes: 0

Sarah Trees
Sarah Trees

Reputation: 904

It seems that the current solution only requires the use of "navigator.clipboard" which also works in the current EDGE.

 navigator.clipboard.writeText('my text to be written to the clipboard ...')
                                                .then(() => { alert('Copy successful'); })
                                                .catch((error) => { alert(`Copy failed! ${error}`); });

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/write

Upvotes: 3

Related Questions