2011-08-22 56 views
15

我試圖使用execcommand("paste")將剪貼板數據粘貼到textarea中,但是我似乎無法使其工作。 權限已設置。 我試圖在textarea上設置focus(),但document.execCommand("paste")什麼都不做,我沒有任何錯誤。 從背景頁面調用execcommand("paste")也什麼都不做。在Chrome擴展中正確使用execcommand(「粘貼」)

<form> 
    <textarea id="ta"></textarea>  
</form> 
<script type="text/javascript"> 
    document.findElemetById("ta").focus(); 
    document.execCommand("paste"); 
</script> 
+0

小觀察工作,但你的意思'document.getElementById'爲'document.findElementById'不存在?我確定這不是真正的代碼問題,因爲這肯定會導致錯誤。 – Alasdair

+0

也看到這個問題:http://stackoverflow.com/questions/6969403/cant-get-execcommandpaste-to-work-in-chrome/7100464#7100464 –

回答

33

剪貼板功能的my extension的重要組成部分,所以我已經看到了正常的問題。在我的背景頁面上,我公開了copypaste函數,頁面本身包含<textarea id="sandbox"></textarea>;

function copy(str) { 
    var sandbox = $('#sandbox').val(str).select(); 
    document.execCommand('copy'); 
    sandbox.val(''); 
} 

function paste() { 
    var result = '', 
     sandbox = $('#sandbox').val('').select(); 
    if (document.execCommand('paste')) { 
     result = sandbox.val(); 
    } 
    sandbox.val(''); 
    return result; 
} 

我使用jQuery爲了簡單,但你的想法。現在,無論何時我想使用剪貼板功能,我只需調用相關函數即可。我的擴展程序中的其他頁面可以通過chrome.extension.getBackgroundPage()訪問此API,但如果您的背景頁面爲event page,則也可以使用chrome.runtime.getBackgroundPage(callback)

我不確定這是否是最佳實踐,或者如果這樣的事情甚至存在這種功能,但是這對我來說確實有效,而且非常乾淨。

+0

非常感謝你 我could'nt讓你的代碼工作開箱,但改變 result = sandbox.val(); 至 result = $(「#sandbox」)。VAL(); 做伎倆 – monopoint

+0

啊,救命啊!有一個問題,我複製了一些使用textarea style ='display:none;'的其他代碼這停止了​​它的工作,但這完美的伎倆! – iono

+0

確保您也設置了您的權限。 「權限」:[「clipboardWrite」] –

17

對於Alasdair的出色反應評論太長了,所以我正在創造另一個答案。 Alasdair的答案非常好,對我來說非常合適,但作爲Chrome擴展的新手,我仍需要一段時間才能實現它。對於任何處於類似位置的人來說,這裏是對他的回答的擴展。

如果您已經請求適當的權限,背景/活動頁面可以與系統剪貼板交互。他們無法與用戶加載的頁面的DOM進行交互。內容腳本不能與系統剪貼板交互,但可以與用戶加載的頁面的DOM進行交互。請看explanation of the extension architecture,以便對這一切有一個很好的概述。

這基本上意味着您需要從事件/背景頁面中的系統剪貼板執行復制/粘貼操作,這正是Alasdair上面概述的。從用戶正在查看的頁面的DOM的任何粘貼或複製都必須發生在您的內容腳本中。這兩個腳本能夠很容易地與message passing進行通信。

我有an extension其唯一目的是粘貼,架構主要來自這篇文章。如果您想在實踐中看到上述技術,請撥打take a look at the code。特別地,background.html,background.jscontentscript.js

如果您真的很匆忙,here is a gist

+2

+1提供一個有用的例子 – schellmax

0
function PasteString() { 
    var editor = document.getElementById("TemplateSubPage"); 
    editor.focus(); 
    // editor.select(); 
    document.execCommand('Paste'); 
} 

function CopyString() { 
    var input = document.getElementById("TemplateSubPage"); 
    input.focus(); 
    // input..select(); 
    document.execCommand('Copy'); 
    if (document.selection) { 
     document.selection.empty(); 
    } else if (window.getSelection) { 
     window.getSelection().removeAllRanges(); 
    } 
} 

希望這會爲你