1

I was searching for how in a Chrome App to use javascript to simply get the current text from the clipboard. Although I did a fair bit of searching I was not able to find a solution that was current, complete and adaptable to various scenarios. So, I thought I'd ask and answer the question here for the hopeful benefit of others.

Here are some related questions (most to least related):

Community
  • 1
  • 1
danf
  • 293
  • 3
  • 12

1 Answers1

3

This will work in Chrome 39 and above.

First you need to put the "clipboardRead" permission into the permissions section of the manifest file. See these links for more details on that: https://developer.chrome.com/apps/manifest and https://developer.chrome.com/apps/declare_permissions

Then, you can use this function:

// getClipboardText - return any text that is currently on the clipboard
function getClipboardText() {
    // create div element for pasting into
    var pasteDiv = document.createElement("div");

    // place div outside the visible area
    pasteDiv.style.position = "absolute";
    pasteDiv.style.left = "-10000px";
    pasteDiv.style.top = "-10000px";

    // set contentEditable mode
    pasteDiv.contentEditable = true;

    // find a good place to add the div to the document
    var insertionElement = document.activeElement; // start with the currently active element
    var nodeName = insertionElement.nodeName.toLowerCase(); // get the element type
    while (nodeName !== "body" && nodeName !== "div" && nodeName !== "li" && nodeName !== "th" && nodeName !== "td") { // if have not reached an element that it is valid to insert a div into (stopping eventually with 'body' if no others are found first)
        insertionElement = insertionElement.parentNode; // go up the hierarchy
        nodeName = insertionElement.nodeName.toLowerCase(); // get the element type
    }

    // add element to document
    insertionElement.appendChild(pasteDiv);

    // paste the current clipboard text into the element
    pasteDiv.focus();
    document.execCommand('paste');

    // get the pasted text from the div
    var clipboardText = pasteDiv.innerText;

    // remove the temporary element
    insertionElement.removeChild(pasteDiv);

    // return the text
    return clipboardText;
}
danf
  • 293
  • 3
  • 12
  • Why not paste into a textarea or input element, instead of in a contentEditable div? That's what the answer at [this](https://stackoverflow.com/questions/22702446/how-to-get-clipboard-data-in-chrome-extension) question does. – ShreevatsaR Jul 21 '17 at 05:12
  • Well I'm not sure why, but this worked while the textarea didn't. Thanks! – ShreevatsaR Jul 21 '17 at 06:40