从chrome app中获取剪贴板中的当前文本

时间:2015-02-19 23:07:00

标签: javascript clipboard google-chrome-app

我在Chrome应用中搜索如何使用javascript从剪贴板中获取当前文本。虽然我做了相当多的搜索,但是我无法找到最新,完整且适应各种场景的解决方案。所以,我想我会在这里提出并回答这个问题,以获得其他人的希望。

以下是一些相关问题(大多数与最不相关):

1 个答案:

答案 0 :(得分:3)

这适用于Chrome 39及更高版本。

首先你需要把#34; clipboardRead"权限进入清单文件的权限部分。有关详细信息,请参阅以下链接:https://developer.chrome.com/apps/manifesthttps://developer.chrome.com/apps/declare_permissions

然后,您可以使用此功能:

// 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;
}