Home  >  Article  >  Web Front-end  >  JavaScript copy content to clipboard implementation code

JavaScript copy content to clipboard implementation code

小云云
小云云Original
2018-02-28 13:14:091239browse

There is a small requirement in a recent activity page. Users can click or long-press to copy the content to the clipboard and record the implementation process and pitfalls encountered.

Common methods

I checked the omnipotent Google, and now the common methods are mainly the following two:

  • Third-party libraries: clipboard.js

  • Native method: document.execCommand()

Let’s see how these two methods are used.

clipboard.js

This is the official website of clipboard: https://clipboardjs.com/, it seems so simple.

Quote

Direct quote:

Package : npm install clipboard --save, then import Clipboard from 'clipboard';

Use

to copy

## from the input box #Now there is an

tag on the page, we need to copy the content inside it, we can do this:


import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
Notice that in

import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
this.copyValue = 'hello world';
Event

Sometimes we need to do something after copying, then we need the support of callback function.

Add the following code to the processing function:

// 复制成功后执行的回调函数
clipboard.on('success', function(e) {
    console.info('Action:', e.action); // 动作名称,比如:Action: copy
    console.info('Text:', e.text); // 内容,比如:Text:hello word
    console.info('Trigger:', e.trigger); // 触发元素:比如:
    e.clearSelection(); // 清除选中内容
});

// 复制失败后执行的回调函数
clipboard.on('error', function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
});
Summary

The document also mentions that if

clipboard is used in a single page, in order to make Life cycle management is more elegant. Remember btn.destroy() to destroy it after use.

clipboard Isn’t it very simple to use? However, is it not elegant enough to use additional third-party libraries just for a copy function? What should I do at this time? Then use native methods to achieve it.

document.execCommand() method

Let’s first look at how this method is defined on

MDN:

which allows one to run commands to manipulate the contents of the editable region.
means that you can allow running commands to manipulate the contents of the editable region. Note that it is

editable region.

Definition

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
The method returns a

Boolean value, indicating whether the operation was successful.

  • aCommandName: Represents the command name, such as: copy, cut, etc. (see commands for more commands);

  • aShowDefaultUI: Whether to display the user interface, usually false;

  • aValueArgument: Some commands require additional parameters, which are generally not used;

Compatibility

The compatibility of this method before was actually not That's great, but fortunately it is now basically compatible with all major browsers and can also be used on mobile devices.

JavaScript copy content to clipboard implementation code

Copy from the input box using

Now there is an

on the page tag, we want to copy the content, we can do this:


const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
    const input = document.querySelector('#demoInput');
    input.select();
    if (document.execCommand('copy')) {
        document.execCommand('copy');
        console.log('复制成功');
    }
})
Copy elsewhere

Sometimes there is no

## on the page # tag, we may need to copy the content from a

, or copy the variable directly. Remember in the definition of the

execCommand()

method that it can only operate editable areas, which means that except and