2015-02-19 3 views
1

Я искал, как в приложении Chrome использовать javascript, чтобы просто получить текущий текст из буфера обмена. Несмотря на то, что я сделал небольшой поиск, я не смог найти решение, которое было текущим, полным и адаптируемым к различным сценариям. Итак, я подумал, что я попрошу и отвечу на этот вопрос здесь для обнадеживающей выгоды других.Получить текущий текст из буфера обмена в chrome app

Вот некоторые вопросы (большинство наименее связанных):

ответ

3

Это будет работать в Chrome 39 и выше.

Сначала вам нужно поместить разрешение «clipboardRead» в раздел разрешений файла манифеста. Смотрите эти ссылки для получения более подробной информации о том, что: https://developer.chrome.com/apps/manifest и https://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; 
} 
+0

Почему бы не вставить в элемент TEXTAREA или ввода, а не в contentEditable DIV? Вот что ответил на вопрос [this] (https://stackoverflow.com/questions/22702446/how-to-get-clipboard-data-in-chrome-extension). – ShreevatsaR

+0

Ну, я не уверен, почему, но это сработало, в то время как в textarea этого не было. Благодаря! – ShreevatsaR

Смежные вопросы