JS copy and paste function implementation

JS copy and paste function implementation

This chapter records how to copy content to the clipboard through js code, and then paste it where needed.

Divided into two parts:

  • The first two parts use the execCommand method, which is now deprecated (ps: although it can still be used), and the copying of single-line content needs to be combined with the input tag, and the copying of multi-line content needs to be combined with the textarea tag.

  • The third part is now using the Clipboard API to copy single or multiple lines of content. (recommended method)

1-execCommand method

This method is a method under the document object and has been deprecated. However, considering that such a method has been used to implement the copy function before, it is also written here and is still available.

Single line copy

Pass the content to be copied to the value attribute through the input tag, and then execute the copy function through the execCommand method under the document object.

The specific implementation is as follows:

handleCopy() {
    
    
  let copy_text = '需要复制的内容';//拿到想要复制的值
  
  let input_dom = document.createElement('input');//创建input元素
  input_dom.value = copy_text;//添加需要复制的内容到value属性
  document.body.appendChild(input_dom);//向页面底部追加输入框
  input_dom.select();//选择input元素
  document.execCommand("Copy");//执行复制命令
  alert("复制成功!");//弹出提示信息,不同组件可能存在写法不同
  
  //复制之后再删除元素,否则无法成功赋值
  input_dom.remove();//删除动态创建的节点
},

The above method can be added to the corresponding mouse event when the page needs to trigger the copy function.

Copy multiple lines

Pass the content that needs to be copied to the value attribute through the textarea tag, and add the newline character \r\n after the content that needs to be newlined , and then execute the copy function through the execCommand method under the document object.

The specific implementation is as follows:

handleCopy() {
    
    
  let copy_text = '第一行需要复制的内容\r\n第二行需要复制的内容';//拿到想要复制的值
  
  let textarea_dom = document.createElement('textarea');//创建textarea元素
  document.body.appendChild(textarea_dom);//向页面底部追加输入框
  textarea_dom.value = copy_text; //添加需要复制的内容到value属性
  textarea_dom.select();//选择input元素
  document.execCommand("Copy");//执行复制命令
  alert("复制成功!");//弹出提示信息,不同组件可能存在写法不同
  
  //复制之后再删除元素,否则无法成功赋值
  document.body.removeChild(textarea_dom); //删除动态创建的节点
}

The above method can be added to the corresponding mouse event when the page needs to trigger the copy function.

2-Clipboard API (recommended)

The navigator.clipboard.writeText method in the Clipboard API can more easily implement single-line and multi-line content copying, and this method will return a Promise object, which can help us simply handle the content that needs to be executed after the copy is successful or fails.

The specific implementation is as follows:

handleCopy() {
    
    
  let copy_text = '第一行需要复制的内容\r\n第二行需要复制的内容';//拿到想要复制的值
  
  // 使用Clipboard API复制文本到剪贴板中
  navigator.clipboard.writeText(copy_text).then(() => {
    
    
    alert("复制成功!")
  }).catch((err)=>{
    
    
    alert("复制失败!")
  })
}

The above method can be added to the corresponding mouse event when the page needs to trigger the copy function, and the implementation of line breaks is directly supported in the copied content.

Notice:

The above navigator.clipboard.writeText method will only have a clipboard object under the browser's navigator object; if you call the clipboard object like the above method in a front-end framework such as vue, react, etc., it will not exist.

Because the navigator object in the environment where js is written in this type of front-end framework does not provide a clipboard object, and the clipboard object is not a standard property or method of the navigator object.

Therefore, the need to use the Clipboard API in this type of framework needs to be implemented through third-party dependency methods.

The following is an example of using the Clipboard API in a common vue framework:

1. First, rely on the third-party Clipboard

npm install clipboard --save

2. Introduce it in the page file or globally in main.js

import Clipboard from 'clipboard'

3. In the method that needs to implement the copy function, write the implementation

<template>
	<div>
    <div class="copy_dom" @click="handleCopy"></div>
  </div>
</template>

<script>
import Clipboard from 'clipboard';
export default {
    
    
  data: {
    
    
    clipboard: null
  }
  methods: {
    
    
  	handleCopy() {
    
    
      // 传递事件绑定的元素class名和需要复制的内容text,创建Clipboard实例 
	  this.clipboard = new Clipboard('.copy_dom', {
    
    
        text: () => {
    
    
          return '第一行需要复制的内容\r\n第二行需要复制的内容'
        }
      });
      // 复制成功后的回调函数
      this.clipboard.on('success', () => {
    
    
        // 释放内存,非常重要,不然会重复触发回调函数
		this.clipboard.destroy();
        console.log('复制成功!');
      })
     	// 复制失败后的回调函数
      this.clipboard.on('error', function(e) {
    
    
        console.log('复制失败!');
      })
		}
  },
  //beforeDestroy() {
    
    
  //  this.clipboard.destroy(); //组件页面销毁时,需要手动清理clipboard,释放内存
  //}
}
</script>

In the above code, after the clipboard instance is copied successfully, it is recommended to execute the destroy method of instance destruction in the success callback function; you can also execute the destruction method in the beforeDestroy life cycle after the page component is closed.

Guess you like

Origin blog.csdn.net/qq_44886882/article/details/131328261