我的分机有问题。我想从剪贴板粘贴数据。
到目前为止,我已经得到了这个:
function pasteAndGo()
{
document.execCommand('paste')
alert("Pasted")
}
出现警报,但没有粘贴任何内容。
我有一种感觉,
document
部分需要改变,但我不知道该怎么做。有什么想法吗?
出于安全考虑,“合理”的浏览器不支持调用
document.execCommand("paste")
,因为它可能使脚本能够从剪贴板读取敏感数据(如密码)。
这是关于剪贴板事件的document.execCommand("...")
的
兼容性矩阵:
“复制” | “粘贴” | “切” | |
---|---|---|---|
IE | 好的 | 好的 | n/a |
边缘 | 好的 | n/a | 好的 |
火狐 | 好的 | n/a | 好的 |
铬 | 好的 | n/a | 好的 |
我的两分钱:
document.queryCommandSupported 方法功能检测可能的命令。
编辑: 根据 MDN document.queryCommandSupported
现已弃用,不应再使用。
Chrome 已转向更标准的
document.execCommand('paste')
、
document.execCommand('copy')
和
document.execCommand('cut')
命令:
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;
};
当然,您的扩展程序仍然需要“clipboardRead”权限,并且您必须使用消息传递将此信息返回到您的内容脚本:
内容.js:
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));
}
});
背景.js:
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);
clipboardRead
权限才能使用
document.execCommand('paste')
,以及
clipboardWrite
权限才能使用
execCommand('copy')
和
execCommand('cut')
。否则,权限将被拒绝并且不会发生任何事情。
function myPaste() {
navigator.clipboard.readText()
.then(clipText => {
const el = document.activeElement;
if (el.nodeName === 'INPUT') {
const newCursorPos = el.selectionStart + clipText.length;
el.value =
el.value.substring(0, el.selectionStart) +
clipText +
el.value.substring(el.selectionEnd);
el.setSelectionRange(newCursorPos, newCursorPos);
}
});
}
对于#1,添加一个侦听器来拦截用户的粘贴尝试:
addEventListener("paste", pasteHandler);
function pasteHandler(e) {
e.preventDefault();
myPaste();
}
对于#4,将其添加到
el.setSelectionRange(newCursorPos, newCursorPos);
之后:
el.dispatchEvent(new Event('input'));
el.dispatchEvent(new Event('change'));
请注意,如果您使用基于数据绑定代表您操作 DOM 的响应式框架,则需要将光标位置更新推迟到下一次 DOM 渲染之后。例如:
Vue.nextTick(() => {
el.setSelectionRange(newCursorPos, newCursorPos);
});
navigator.clipboard
.readText()
.then(
(clipText) => console.log(clipText)
);