Write text to Clipboard

javascript paste from clipboard
copy to clipboard
copy text to clipboard javascript
javascript copy variable to clipboard
javascript copy to clipboard without input
document execcommand copy' not working
copy url to clipboard javascript
html5 copy to clipboard

I want to write some text variable into clipboard via Chrome Extension, it will be happened when user presses a short-key. I've done all parts except writing to clipboard.

I've searched entire StackOverflow using these keywords: "[google-chrome-extension] Clipboard"

So I want to say, I've seen all related to:

  • Add clipboardRead and clipboardWrite permission (already done)
  • Add text into a <textarea>, call document.execCommand('Copy'); or document.execCommand("Copy", false, null);

Even I tried my extension on StackOverflow's textarea and I inserted my text into wmd-input part of StackOverflow textarea, then selected it, then called copy. Nothing, nothing, nothing...

Everything tried. Please advise... What am I missing?

You can try the following code, it writes text to clipboard

As an example i wrote Sample to clipboard

Output

manifest.json

manifest file is key for all chrome extensions, ensured it is with all permissions

 {
  "name": "Copy to ClipBoard Demo",
  "description" : "This is used for demonstrating Copy to Clip Board Functionality",
  "version": "1",
  "browser_action": {
    "default_popup": "popup.html"
  },
  "permissions":["clipboardWrite"],
    "manifest_version": 2
}
popup.html

A trivial Browser action HTML File, with input box and button

<html>

    <head>
        <script src="popup.js"></script>
    </head>

    <body>
        <input type="text" id="text" placeHolder="Enter Text To Copy"></input>
        <button id="copy">Copy</button>
    </body>

</html>
popup.js

It copies content in <input> to clipboard

function copy() {

    //Get Input Element
    var copyDiv = document.getElementById('text');

    //Give the text element focus
    copyDiv.focus();

    //Select all content
    document.execCommand('SelectAll');

    //Copy Content
    document.execCommand("Copy", false, null);
}

//Add Event Listeners to Button Click
document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("copy").onclick = copy;
});
OR
function copy(){

    //Get Input Element
    document.getElementById("text").select();

    //Copy Content
    document.execCommand("Copy", false, null);
}

//Add Event Listeners to Button Click
document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("copy").onclick = copy;
});

Interact with the clipboard, Write text to Clipboard. Add clipboardRead and clipboardWrite permission (already done) Add text into a <textarea> , call document. execCommand('Copy'); or document. execCommand("Copy", false, null); Clipboard.writeText () The Clipboard interface's writeText () property writes the specified text string to the system clipboard. Note: The specification requires the Permissions API be used to obtain the "clipboardWrite" permission before writing to the clipboard. However, exact requirements vary from browser to browser, since this is a new API.

Based on https://stackoverflow.com/a/12693636

function directCopy(str){
    //based on https://stackoverflow.com/a/12693636
        document.oncopy = function(event) {
    event.clipboardData.setData("Text", str);
    event.preventDefault();
        };
    document.execCommand("Copy");
        document.oncopy = undefined;
}

What does 'Copied to Clipboard' mean?, let textToCopy = 'Copy me' async function copyToClipboard() { try { // 1) Copy text await navigator.clipboard.writeText(textToCopy); // 2) Catch  Login Form Signup Form Checkout Form Contact Form Social Login Form Register Form Form with Icons Newsletter Stacked Form Responsive Form Popup Form Inline Form Clear Input Field Hide Number Arrows Copy Text to Clipboard Animated Search Search Button Fullscreen Search Input Field in Navbar Login Form in Navbar Custom Checkbox/Radio Custom

Suonds like you're trying to copy from a content script. Building off joelpt and Jeff Gran's answers from this answer, here's how to copy any piece of text from a content script:

"permissions": [
    "clipboardWrite",...

In your main.js or any background script:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
  var copyFrom = document.createElement("textarea");
  copyFrom.textContent = request.text;
  var body = document.getElementsByTagName('body')[0];
  body.appendChild(copyFrom);
  copyFrom.select();
  document.execCommand('copy');
  body.removeChild(copyFrom);
})

From your content script:

chrome.runtime.sendMessage({text:textToCopy});

Write text to Clipboard, To copy text to the clipboard call writeText() . Since this API is asynchronous, the writeText() function  I want to write some text variable into clipboard via Chrome Extension, it will be happened when user presses a short-key. I've done all parts except writing to clipboard. I've searched entire StackOverflow using these keywords: "[google-chrome-extension] Clipboard" So I want to say, I've seen all related to:

Usage example:

copyStringToClipboard("abc123");

    function copyStringToClipboard (str) {
      // Create new element
      var el = document.createElement('textarea');
      // Set value (string to be copied)
      el.value = str;
      // Set non-editable to avoid focus and move outside of view
      el.setAttribute('readonly', '');
      el.style = {position: 'absolute', left: '-9999px'};
      document.body.appendChild(el);
      // Select text inside element
      el.select();
      // Copy text to clipboard
      document.execCommand('copy');
      // Remove temporary element
      document.body.removeChild(el);
    }

Copy Text to Clipboard, Subscribe to get your daily round-up of top tech stories! Help · About · Start Writing · Sponsor: · Brand-as-Author · Sitewide Billboard · Ad by tag  Clipboard.js is a modern approach to copy text to clipboard without Flash, it has no dependencies and is lightweight. To initialize clipboard.js, use the following code: Clipboard constructor expects a dom selector as first parameter. In this case all the items with class btn will copy text into the clipboard.

How to easily copy text to clipboard, Writing to the Clipboard. Writing to the clipboard is as simple as calling writeText with the text to write to the clipboard: navigator.clipboard.writeText  The following code writes the string "This is a test string" to the Clipboard as RTF text. My.Computer.Clipboard.SetText("This is a test string.", System.Windows.Forms.TextDataFormat.Rtf) Use the SetData method to write data to the Clipboard. This example writes the DataObject dataChunk to the Clipboard in the custom format specialFormat.

Unblocking Clipboard Access | Web, In order to copy a text from an input element or a textarea on DOM, you can use You can call writeText() method to copy text to the clipboard which uses an  The de facto way to copy text to the clipboard on the web has been to use document.execCommand, but a major caveat is that the operations are synchronous and blocking. Async clipboard is a promise -based API that aims to fix that and also give us a simpler and unified API.

Copying text to clipboard with JavaScript, Set its value to the string that we want to copy to the clipboard. Append said <​textarea> element to the current HTML document. Use  Text To The Clipboard There may be instances where you create a macro that reads in text and sticks it in your computer's clipboard so you can manually paste it somewhere else. The most prominent way to do this, is to use a DataObject variable from the Forms library (language).

Comments
  • Thanks Sudarshan, it worked on Popup, but I already have a variable (output) from content script which I want to copy that text to clipbaord, how I should do that?
  • @DavidBrisker: You mean to say, you have content to be copied is in content scripts variable?
  • I copied your work in background js and it worked well. But in background page I cannot receive keyboard event. I want copying happen when user presses a keyboard shortcut
  • @DavidBrisker: If you can edit your question with code which is not working, it can help me better to understand problem, can you please put your relevant code by editing your question? I can pick it up from there
  • Ok, you can also try this approach var texttobecopied = $('#someid').val(str).select(); document.execCommand('copy'); to copy from content script(s), but i did not test it :)..Edited by answer with another approach