Javascript 如何在Chrome扩展中获取剪贴板数据?
我很难找到任何关于如何为“Ctrl+C”添加侦听器的最新信息,获取剪贴板数据,然后写回剪贴板,所有这些都在Chrome扩展中。我发现的所有旧代码都是针对现在已弃用的旧版本的。基本上,您可以使用Javascript 如何在Chrome扩展中获取剪贴板数据?,javascript,google-chrome,google-chrome-extension,clipboard,Javascript,Google Chrome,Google Chrome Extension,Clipboard,我很难找到任何关于如何为“Ctrl+C”添加侦听器的最新信息,获取剪贴板数据,然后写回剪贴板,所有这些都在Chrome扩展中。我发现的所有旧代码都是针对现在已弃用的旧版本的。基本上,您可以使用document.execCommand('paste | copy | cut')操作剪贴板。 您需要在清单中指定“剪贴板写入”和/或“剪贴板读取” 如果扩展或应用程序使用document.execCommand('paste'),则需要“clipboardRead” “clipboardWrite”表
document.execCommand('paste | copy | cut')操作剪贴板。
- 您需要在清单中指定
和/或“剪贴板写入”
如果扩展或应用程序使用document.execCommand('paste'),则需要“clipboardRead” “clipboardWrite”表示扩展或应用程序使用document.execCommand('copy')或document.execCommand('cut')。托管应用程序需要此权限;建议将其用于扩展和打包应用程序“剪贴板读取”
- 创建
元素(或
) - 把重点放在它上面
- 调用
document.execCommand('paste')
- 从
属性抓取字符串值
这对我将数据复制到剪贴板起到了作用。要在chrome扩展中读取剪贴板文本,您必须:
- 在您的清单中请求“剪贴簿读取”权限
- 创建背景脚本,因为只有背景脚本可以访问剪贴板
- 在背景页中创建一个元素以接受剪贴板粘贴操作。如果将其设置为textarea,则会得到纯文本,如果将其设置为contentEditable=true的div,则会得到格式化的HTML
- 如果要将剪贴板数据传递回页内脚本,则需要使用消息传递API
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;
这里有一个非常简单的解决方案。它只需要您的权限包括
“剪贴簿读”
和“剪贴簿写”
。copyTextToClipboard
功能取自此处:
请注意,
document.execCommand(“粘贴”)
在Chrome中被禁用,并且只能在Chrome扩展中工作,不能在网页中工作。我找到的最佳可行示例是
下面的例子对我很有用,在这里分享,以便有人能得到帮助
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;
}
我可以使用“粘贴”从剪贴板中提取数据吗?是的,应该可以。我已经更新了答案。否则我不明白为什么chrome需要
clipboardWrite
权限。要粘贴剪贴板内容,您需要读取剪贴板的权限,而不是写入权限。。我更新了答案。为了让il更清楚:如果你想复制到剪贴板,你需要写权限在background.js中添加两个示例你不需要获取和使用变量bg,只需要使用document。
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;
}