Javascript – Why document.execCommand(‘paste’) is not working in the extension

google-chrome-extensionjavascript

I am creating a Google chrome extension which can read the contents of clipboard.
But I am unable to get the documentation for this. I want to get the clipboard content as in IE's clipboard API.
In the manifest file i gave permissions to

clipboardRead and clipboardWrite.  

I have created a function in Background page as below

 chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
 if (request.method == "getClipData")
   sendResponse({data: document.execCommand('paste')});
 else
   sendResponse({}); // snub them.
 });

And in Content Script I am calling the function like this

 chrome.extension.sendRequest({method: "getClipData"}, function(response) {
    alert(response.data);
 });

But this returns me undefined…

Best Answer

document.execCommand('paste') returns success or failure, not the contents of the clipboard.

The command triggers a paste action into the focused element in the background page. You have to create a TEXTAREA or DIV contentEditable=true in the background page and focus it to receive the paste content.

You can see an example of how to make this work in my BBCodePaste extension:

https://github.com/jeske/BBCodePaste

Here is one example of how to read the clipboard text in the background page:

bg = chrome.extension.getBackgroundPage();        // get the background page
bg.document.body.innerHTML= "";                   // clear the background page

// add a DIV, contentEditable=true, to accept the paste action
var helperdiv = bg.document.createElement("div");
document.body.appendChild(helperdiv);
helperdiv.contentEditable = true;

// focus the helper div's content
var range = document.createRange();
range.selectNode(helperdiv);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
helperdiv.focus();    

// trigger the paste action
bg.document.execCommand("Paste");

// read the clipboard contents from the helperdiv
var clipboardContents = helperdiv.innerHTML;

If you want plain-text instead of HTML, you can either use helperdiv.innerText, or you can switch to using a textarea. If you want to parse the HTML in some way, you can walk the HTML dom inside the DIV (again, see my BBCodePaste extension)