问题描述
我正在尝试使用带有 chome 扩展名的 execcommand("paste")
将剪贴板数据粘贴到文本区域中,但我似乎无法让它工作.权限设置.我试图在 textarea 上设置 focus()
,但 document.execCommand("paste")
什么也没做,我没有得到任何错误.从后台页面调用 execcommand("paste")
也没有任何作用.
I'm trying to paste clipboard data into a textarea using execcommand("paste")
with a chome extension, but i cannot seem to get it to work. permissions are set. I have tried to set focus()
on the textarea, but document.execCommand("paste")
does nothing, and I get no error.calling execcommand("paste")
from background page also does nothing.
<form>
<textarea id="ta"></textarea>
</form>
<script type="text/javascript">
document.findElemetById("ta").focus();
document.execCommand("paste");
</script>
推荐答案
剪贴板功能是我的扩展程序的关键部分 所以我已经看到了所有的正常问题.在我的背景页面上,我公开了一个 copy
和一个 paste
函数,页面本身包含 <textarea id="sandbox"></textarea>
;
Clipboard functionality is a key part of my extension so I've seen all the normal problems. On my background page I expose a copy
and a paste
function and the page itself contains <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,但您也可以使用chrome.runtime.getBackgroundPage(callback) 如果您的背景页面是 活动页面.
I'm using jQuery for simplicity but you get the idea. Now any time I want to use the clipboard functionality I simply call the relevant function. Other pages in my extension can access this API via chrome.extension.getBackgroundPage() but you can also use chrome.runtime.getBackgroundPage(callback) if your background page is an event page.
我不确定这是否是最佳实践,或者该功能是否存在这样的东西,但这绝对适合我并且非常干净.
I'm not sure if this is best practice or if such a thing even exists for this functionality yet but this definitely works for me and is very clean.
这篇关于在 chrome 扩展中正确使用 execcommand(“paste")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!