html获得剪切板数据,JS 获取chrome剪切板数据

 2023-09-05 阅读 90 评论 0

摘要:希望使用JS获取chrome浏览器中剪切板的数据,数据为字符串类型,求大神帮忙解答…整理自之前自己的一段代码,保证了绝大部分的兼容性。uploader上传用你们自己组件吧// 粘贴事件的监听ele.on('paste', pasteHandle);// 粘贴复制上传等功能function

希望使用JS获取chrome浏览器中剪切板的数据,数据为字符串类型,求大神帮忙解答…

整理自之前自己的一段代码,保证了绝大部分的兼容性。

uploader上传用你们自己组件吧

// 粘贴事件的监听

ele.on('paste', pasteHandle);

// 粘贴复制上传等功能

function pasteHandle(ev) {

let cbd = ev.originalEvent.clipboardData;

let ua = window.navigator.userAgent;

ev.stopPropagation();

ev.preventDefault();

// 如果是 Safari 直接 return

if (!cbd || !cbd.items || !cbd.types) return;

// Mac平台下Chrome49版本以下 复制Finder中的文件的Bug Hack掉

if (cbd.items.length === 2 && cbd.items[0].kind === 'string' && cbd.items[1].kind === 'file' && cbd.types.length === 2 && cbd.types[0] === 'text/plain' && cbd.types[1] === 'Files' &&

ua.match(/Macintosh/i) && ~~(ua.match(/Chrome\/(\d{2})/i)[1]) < 49) return;

for (let i = 0, len = cbd.items.length; i < len; i++) {

let item = cbd.items[i];

// 文件类型上传

if (item.kind === 'file') {

let blob = item.getAsFile();

if (blob.size === 0) return;

let fileName = cbd.getData('text/plain');

// 上传文件

return uploader(blob, { name: fileName });

}

}

let text = cbd.getData('text/plain');

// 复制文字

if (text) insertTextCMD(text);

}

function insertTextCMD(text) {

if (document.body.createTextRange) {

let textRange;

if (document.selection) {

textRange = document.selection.createRange();

} else if (window.getSelection) {

let sel = window.getSelection();

let range = sel.getRangeAt(0);

// 创建临时元素,使得TextRange可以移动到正确的位置

let tempEl = document.createElement('span');

tempEl.innerHTML = '&#FEFF;';

range.deleteContents();

range.insertNode(tempEl);

textRange = document.body.createTextRange();

textRange.moveToElementText(tempEl);

tempEl.parentNode.removeChild(tempEl);

}

textRange.text = text;

textRange.collapse(false);

textRange.select();

} else {

// Chrome之类浏览器

document.execCommand('insertText', false, text);

}

}

自己都想给自己一个赞加收藏,23333

ZeroClipboard

950-390_%E7%94%BB%E6%9D%BF-1.jpg

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/300.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息