sch*_*erj 16 javascript clipboard google-chrome google-chrome-extension
我很难找到有关如何为"Ctrl + C"添加监听器,获取剪贴板数据,然后在Chrome扩展程序中写回剪贴板的最新信息.我找到的所有旧代码都是针对旧版本的,现在已弃用.
Iva*_*uev 22
基本上你可以使用操纵剪贴板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属性中获取字符串.这对我来说可以将数据复制到剪贴板.
要在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;
Run Code Online (Sandbox Code Playgroud)
这是一个非常简单的解决方案。它所需要的只是您的权限包括"clipboardRead"和"clipboardWrite"。该copyTextToClipboard函数取自此处:/sf/answers/1291856191/
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);
Run Code Online (Sandbox Code Playgroud)
请注意,该功能document.execCommand("paste")在 Chrome 中被禁用,并且只能在 Chrome 扩展程序中使用,而不能在网页中使用。
| 归档时间: |
|
| 查看次数: |
7754 次 |
| 最近记录: |