js触发复制、粘贴,设置和读取剪切板的数据

程序员的众多称号里的一个叫“CV战神”,但又有多少人知道cv的更多东西呢?

一起来看下cv下还隐含多少东西:

  1.复制一段文字到剪切板

  2.直接往剪切板写一段内容

  3.从剪切板获取内容

复制文本到剪切板:

 1     // 复制内容到剪切板
 2     copyFn(value){
 3         let transfer = document.createElement(‘input‘);
 4         document.body.appendChild(transfer);
 5         transfer.value = value;  // 这里表示想要复制的内容
 6         transfer.focus();
 7         transfer.select();
 8         if (document.execCommand(‘copy‘)) {
 9             document.execCommand(‘copy‘);
10         }
11         transfer.blur();
12         // message.success(‘复制成功‘);
13         document.body.removeChild(transfer);
14     }

通过这个方法会把value复制到剪切板的‘text/plain‘区域,你要是注册了copy的监听,会触发你的监听。

直接将要复制的内容放到剪切板

 1     // 复制内容到剪切板
 2     clipboardWrite(value){
 3         window.navigator.clipboard.writeText(value)
 4         .then(() => {
 5             console.log(‘Text copied to clipboard‘);
 6         })
 7         .catch(err => {
 8             // This can happen if the user denies clipboard permissions:
 9             console.error(‘Could not copy text: ‘, err);
10         });
11     }

通过这个方法会把value复制到剪切板的‘text/plain‘区域,你要是注册了copy的监听,会触发你的监听。

从剪切板获取内容

 1     // 获取剪切板的数据
 2     async pasteHandler(){
 3         const clipboardItems = await window.navigator.clipboard.read();
 4         let textHtml,textPlain;
 5         for (const clipboardItem of clipboardItems) {
 6             for (const type of clipboardItem.types) {
 7                 const item = await clipboardItem.getType(type);
 8                 if(item && item.type == ‘text/html‘){
 9                     textHtml = await item.text();
10                 }
11                 if(item && item.type == ‘text/plain‘){
12                     textPlain = await item.text();
13                 }
14             }
15         }
16         return {textHtml,textPlain}
17     }

方法中item会有四种类型,文本和html还有图片还有什么 ,忘却了,有需要的自己打印看看。

当然navigator.clipboard.readText()直接可以读取‘text/plain’的值,但如果你复制的是Excel的数据的话,通过这个方法获取到的只是一些文本和箭头。

 

研究了半天怎么用js触发ctrl+c和ctrl+v的事件,但也没有效果,哪位大佬成功了望不吝赐教。

 

over!

 

js触发复制、粘贴,设置和读取剪切板的数据

上一篇:VUE JSX基本常用语法


下一篇:json解析库jsonpath