Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在chrome应用程序中从剪贴板获取当前文本_Javascript_Clipboard_Google Chrome App - Fatal编程技术网

Javascript 在chrome应用程序中从剪贴板获取当前文本

Javascript 在chrome应用程序中从剪贴板获取当前文本,javascript,clipboard,google-chrome-app,Javascript,Clipboard,Google Chrome App,我在Chrome应用程序中搜索如何使用javascript从剪贴板获取当前文本。虽然我做了一点搜索,但我无法找到一个最新的、完整的、适合各种场景的解决方案。所以,我想我应该在这里问和回答这个问题,希望能给其他人带来好处 以下是一些相关问题(从最相关到最不相关): 这将适用于Chrome 39及以上版本 首先,您需要将“clipboardRead”权限放入清单文件的权限部分。请参阅这些链接以了解更多详细信息:和 然后,您可以使用此功能: // getClipboardText - retu

我在Chrome应用程序中搜索如何使用javascript从剪贴板获取当前文本。虽然我做了一点搜索,但我无法找到一个最新的、完整的、适合各种场景的解决方案。所以,我想我应该在这里问和回答这个问题,希望能给其他人带来好处

以下是一些相关问题(从最相关到最不相关):


这将适用于Chrome 39及以上版本

首先,您需要将“clipboardRead”权限放入清单文件的权限部分。请参阅这些链接以了解更多详细信息:和

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

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

为什么不粘贴到textarea或input元素中,而不是在contentEditable div中?这就是问题的答案。我不知道为什么,但这是有效的,而textarea没有。谢谢