2011-08-22 62 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(); 
    } 
} 

希望这会为你