js实现粘贴
监听粘贴事件
使用addEventListener监听paste事件,可以获取用户粘贴的内容。事件对象包含clipboardData属性,通过getData方法获取剪贴板数据。
document.addEventListener('paste', (event) => {
const clipboardData = event.clipboardData || window.clipboardData;
const pastedText = clipboardData.getData('text');
console.log('粘贴内容:', pastedText);
});
处理富文本粘贴
当需要处理包含格式的富文本内容时,可以通过getData('text/html')获取HTML格式数据。需注意浏览器兼容性。

document.addEventListener('paste', (event) => {
const htmlData = event.clipboardData.getData('text/html');
if (htmlData) {
console.log('富文本内容:', htmlData);
}
});
限制粘贴内容类型
通过检查clipboardData.types可以判断剪贴板中的数据类型,实现选择性粘贴。常见类型包括text/plain和text/html。

document.addEventListener('paste', (event) => {
if (event.clipboardData.types.includes('text/plain')) {
const text = event.clipboardData.getData('text/plain');
// 处理纯文本
}
});
自定义粘贴行为
使用preventDefault()阻止默认粘贴行为,完全自定义处理逻辑。适用于需要清理格式或转换内容的场景。
document.addEventListener('paste', (event) => {
event.preventDefault();
const text = event.clipboardData.getData('text/plain');
// 自定义处理逻辑
document.execCommand('insertText', false, processedText);
});
安全注意事项
处理粘贴内容时应当进行适当的清理和验证,防止XSS攻击。特别是处理HTML内容时,建议使用DOMPurify等库进行净化。
import DOMPurify from 'dompurify';
document.addEventListener('paste', (event) => {
const dirtyHtml = event.clipboardData.getData('text/html');
const cleanHtml = DOMPurify.sanitize(dirtyHtml);
// 使用净化后的HTML
});






