我尝试使用带有chome扩展的execcommand("paste")
将剪贴板数据粘贴到文本区,但似乎无法正常工作。权限已设置。我尝试在文本区域上设置focus()
,但是document.execCommand("paste")
什么也不做,我也没有得到错误。从后台页面调用execcommand("paste")
也不会做任何事情。
<form>
<textarea id="ta"></textarea>
</form>
<script type="text/javascript">
document.findElemetById("ta").focus();
document.execCommand("paste");
</script>
发布于 2011-08-22 20:06:10
剪贴板功能是my extension的关键部分,所以我看到了所有常见的问题。在我的背景页面上,我公开了一个copy
和一个paste
函数,页面本身包含<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)。
我不确定这是不是最好的做法,或者这项功能是否存在这样的东西,但这对我来说肯定是有效的,非常干净。
发布于 2014-07-28 02:12:40
评论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.js和contentscript.js。
如果你真的很着急的话here is a gist
发布于 2016-06-25 16:20:18
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();
}
}
希望这对你有用
https://stackoverflow.com/questions/7144702
复制相似问题