我很难找到有关如何在Chrome扩展中添加“Ctrl+C”监听器、获取剪贴板数据,然后将数据写回剪贴板的最新信息。我找到的所有旧代码都是针对现在已弃用的旧版本。
我很难找到有关如何在Chrome扩展中添加“Ctrl+C”监听器、获取剪贴板数据,然后将数据写回剪贴板的最新信息。我找到的所有旧代码都是针对现在已弃用的旧版本。
你可以使用 document.execCommand('paste|copy|cut')
来操纵剪贴板。
你需要在清单中指定"clipboardWrite"
和/或"clipboardRead"
权限。
"clipboardRead" 如果扩展程序或应用程序使用 document.execCommand('paste') ,则需要此权限。
"clipboardWrite" 表示扩展程序或应用程序使用 document.execCommand('copy') 或 document.execCommand('cut')。 对于托管的应用程序,需要此权限; 对于扩展程序和打包的应用程序,则建议使用此权限。
创建一个<input>
元素(或<textarea>
)
document.execCommand('paste')
<input>
的value
属性中获取字符串。对我来说,这可用于将数据复制到剪贴板。
要查看所有工作示例,请参见我的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://dev59.com/XXA75IYBdhLWcg3wK1wp#18455088
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扩展程序中使用,而不能在网页中使用。function getClipboard() {
var result = null;
var textarea = document.getElementById('ta');
textarea.value = '';
textarea.select();
if (document.execCommand('paste')) {
result = textarea.value;
} else {
console.log('failed to get clipboard content');
}
textarea.value = '';
return result;
}