【发布时间】:2014-03-28 01:18:28
【问题描述】:
我很难找到有关如何为“Ctrl+C”添加侦听器、获取剪贴板数据,然后在 Chrome 扩展中全部写回剪贴板的任何最新信息。我发现的所有旧代码都是针对现已弃用的旧版本的。
【问题讨论】:
标签: javascript google-chrome google-chrome-extension clipboard
我很难找到有关如何为“Ctrl+C”添加侦听器、获取剪贴板数据,然后在 Chrome 扩展中全部写回剪贴板的任何最新信息。我发现的所有旧代码都是针对现已弃用的旧版本的。
【问题讨论】:
标签: javascript google-chrome google-chrome-extension clipboard
基本上,您可以使用document.execCommand('paste|copy|cut') 操作剪贴板。
您需要在清单中指定"clipboardWrite" 和/或"clipboardRead" permissions。
"clipboardRead" 如果扩展程序或应用程序使用 document.execCommand('paste'),则为必需。
"clipboardWrite" 表示扩展或应用使用 document.execCommand('copy') 或 document.execCommand('cut')。托管应用程序需要此权限;推荐用于扩展和打包的应用程序。
创建<input> 元素(或<textarea>)
document.execCommand('paste')
<input> value 属性中获取字符串。这对我来说可以将数据复制到剪贴板。
【讨论】:
clipboardWrite 权限。
要阅读 chrome 扩展程序中的剪贴板文本,您必须:
要查看所有工作的示例,请参阅我的 BBCodePaste 扩展:
https://github.com/jeske/BBCodePaste
以下是如何在后台页面中读取剪贴板文本的一个示例:
bg = chrome.extension.getBackgroundPage(); // get the background page
bg.document.body.innerHTML= ""; // clear the background page
// add a DIV, contentEditable=true, to accept the paste action
var helperdiv = bg.document.createElement("div");
document.body.appendChild(helperdiv);
helperdiv.contentEditable = true;
// focus the helper div's content
var range = document.createRange();
range.selectNode(helperdiv);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
helperdiv.focus();
// trigger the paste action
bg.document.execCommand("Paste");
// read the clipboard contents from the helperdiv
var clipboardContents = helperdiv.innerHTML;
【讨论】:
这是一个非常简单的解决方案。它只需要您的权限包括"clipboardRead" 和"clipboardWrite"。 copyTextToClipboard 函数取自这里:https://stackoverflow.com/a/18455088/4204557
var t = document.createElement("input");
document.body.appendChild(t);
t.focus();
document.execCommand("paste");
var clipboardText = t.value; //this is your clipboard data
copyTextToClipboard("Hi" + clipboardText); //prepends "Hi" to the clipboard text
document.body.removeChild(t);
请注意,document.execCommand("paste") 在 Chrome 中已禁用,并且只能在 Chrome 扩展程序中使用,而不能在网页中使用。
【讨论】:
我发现的最佳可行示例是here 下面的例子对我有用,在这里分享以便有人可以得到帮助
function getClipboard() {
var result = null;
var textarea = document.getElementById('ta');
textarea.value = '';
textarea.select();
if (document.execCommand('paste')) {
result = textarea.value;
} else {
console.error('failed to get clipboard content');
}
textarea.value = '';
return result;
}
【讨论】: