复制事件后修改剪贴板内容:JavaScript,jQuery
我的要求:当用户从我的网页复制某些内容时,带有文本的一些HTML标记和回车符也会被复制。我需要修改剪贴板中复制的内容,即删除回车键和HTML标签。
My requirement: When user copy some content from my web page, with text some HTML tags and carriage retun also gets copied. I need to modify the copied content in clipboard i.e. removing carriage retunn and HTML tags.
到目前为止我已经尝试过:
我什至使用jQuery捕获了副本并获取剪贴板的内容。见下面的代码。
What I have tried so far: I have captured the copy even using jQuery and get the content of clipboard. See below code.
$(document).bind('copy', function () {
//getting clipboard content
var selectedText = window.getSelection().toString();
//removing carriage retun from content
selectedText = selectedText.replace(/<\/?[^>]+(>|$)/g, "");
//Trying to set data in clipboard
window.clipboardData.setData(selectedText); //Throws error
}
现在,当我尝试使用 window.clipboardData.setData(selectedText); ,它会引发错误。
Now, when I tried to setData in clipboard using window.clipboardData.setData(selectedText);
, it throws error.
问题:
1)我是否使用正确的函数,即 setData()
来修改剪贴板内容? / strong>
1) Am I using the correct function i.e. setData()
to modify the clipbard content or not?
2)有人可以让我知道如何在此处修改剪贴板的内容吗?
要解决此问题,我在副本上所做的事情
事件我绑定了一个函数,即 copyToClipboard
,该函数在运行时创建 textarea
,复制修改后的剪贴板数据到此文本区域,然后执行 CUT命令(以避免对复制事件进行递归调用)。最后删除finally块中的textarea元素。
To resolve this issue what I have done on copy
event I have bind a function i.e. copyToClipboard
which creates a textarea
at run time, copy modified clipboard data to this text area and then execute a 'CUT' command (to avoid recursive call on copy event). And finally deleting textarea element in finally block.
代码:
$(document).bind('copy', function () {
var text = window.getSelection().toString().replace(/[\n\r]+/g, '');
copyToClipboard(text);
});
function copyToClipboard(text) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed";
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("cut");
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}