Jos*_*ffy 12 javascript clipboard google-chrome google-chrome-extension
我的扩展程序有问题.我想从剪贴板粘贴数据.
到目前为止,我有这个:
function pasteAndGo()
{
document.execCommand('paste')
alert("Pasted")
}
Run Code Online (Sandbox Code Playgroud)
警报出现,但没有粘贴任何内容.
我感觉这document是需要改变的部分,但我不知道该怎么做.有任何想法吗?
Bor*_*mus 11
曾经有一个Chrome中的实验性剪贴板API,但这在Chrome 13中被删除了.
Chrome浏览器已经转向更标准document.execCommand('paste'),document.execCommand('copy')和document.execCommand('cut')命令:https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla#Executing%5FCommands
在Chrome中,您需要将权限添加到清单中:"clipboardRead"和"clipboardWrite".http://developer.chrome.com/extensions/declare_permissions.html
在Chrome 38之前,这些剪贴板权限仅适用于后台脚本等扩展页面.从Chrome 39开始,内容脚本也可以在清单文件中声明剪贴板权限后使用这些剪贴板API(crbug.com/395376).
这在后台页面中对我很有用.
function getClipboard() {
var pasteTarget = document.createElement("div");
pasteTarget.contentEditable = true;
var actElem = document.activeElement.appendChild(pasteTarget).parentNode;
pasteTarget.focus();
document.execCommand("Paste", null, null);
var paste = pasteTarget.innerText;
actElem.removeChild(pasteTarget);
return paste;
};
Run Code Online (Sandbox Code Playgroud)
当然,您的扩展程序仍需要"clipboardRead"权限,您必须使用消息传递将此信息返回到您的内容脚本:
chrome.extension.sendMessage({
cmd: "clipboard", //$NON-NLS-0$
action: "paste" //$NON-NLS-0$
}, function(response) {
if (response.paste) {
var range = document.getSelection().getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(response.paste));
}
});
Run Code Online (Sandbox Code Playgroud)
function getClipboard() {
var pasteTarget = document.createElement("div");
pasteTarget.contentEditable = true;
var actElem = document.activeElement.appendChild(pasteTarget).parentNode;
pasteTarget.focus();
document.execCommand("Paste", null, null);
var paste = pasteTarget.innerText;
actElem.removeChild(pasteTarget);
return paste;
};
function onClipboardMessage(request, sender, sendResponse) {
if (request.action === "paste") { //$NON-NLS-0$
sendResponse({
paste: getClipboard()
});
}
}
chrome.extension.onMessage.addListener(onClipboardMessage);
Run Code Online (Sandbox Code Playgroud)
document.execCommand("paste")由于安全方面的考虑,“合理的”浏览器不支持调用,因为它可能使脚本能够从剪贴板读取敏感数据(例如密码)。
这是兼容性矩阵的document.execCommand("...")有关剪贴板事件:
| "copy" | "paste" | "cut"
--------+--------+---------+--------
IE | OK | OK | n/a
--------+--------+---------+--------
Edge | OK | n/a | OK
--------+--------+---------+--------
Firefox | OK | n/a | OK
--------+--------+---------+--------
Chrome | OK | n/a | OK
Run Code Online (Sandbox Code Playgroud)
我的两分钱:
您可以使用document.queryCommandSupported方法来检测可能的命令。
| 归档时间: |
|
| 查看次数: |
30328 次 |
| 最近记录: |