Link: github.com/axuebin/art…


In a recent activity page, there was a small requirement that the user could copy the content to the clipboard with a click or long press, and record the implementation and the craters encountered.

Common methods

Check the omnipotent Google, now the common methods are mainly the following two:

  • Third-party library: clipboard.js
  • Native method: document.execCommand()

Take a look at how these two methods are used.

clipboard.js

This is clipboard’s official website: clipboardjs.com/, and it looks that simple.

reference

NPM install clipboard –save, then import clipboard from ‘clipboard’;

use

Copy from the input box

Now that we have an tag on the page, we need to copy the content. We can do this:

<input id="demoInput" value="hello world">
<button class="btn" data-clipboard-target="#demoInput">Let me copy</button>
Copy the code
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
Copy the code

Notice that a data-clipboark-target attribute has been added to the

Direct copy

Sometimes, we don’t want to copy content from , just value it directly from the variable. If in Vue we can do this:

<button class="btn" :data-clipboard-text="copyValue">Let me copy</button>
Copy the code
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
this.copyValue = 'hello world';
Copy the code

The event

There are times when we need to do something after the copy, when we need support for callback functions.

Add the following code to the handler:

// The callback function to execute after the replication is successful
clipboard.on('success'.function(e) {
    console.info('Action:', e.action); // Action name, for example: Action: copy
    console.info('Text:', e.text); // Content, such as: Text: hello word
    console.info('Trigger:', e.trigger); 
    e.clearSelection(); // Clear the selected content
});

// The callback function to execute after the replication failed
clipboard.on('error'.function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
});
Copy the code

summary

If you’re using Clipboard on a single page, remember to btn.destroy() after you use it for more elegant lifecycle management.

Clipboard is easy to use. But what if it’s not elegant to use additional third-party libraries just for copy? Do it native.

Document. ExecCommand () method

Let’s see how this method is defined in MDN:

which allows one to run commands to manipulate the contents of the editable region.

This means that you can run commands to manipulate the contents of the editable region.

define

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

Method returns a Boolean value indicating whether the operation was successful.

  • aCommandName: indicates the command name, for example:copy.cutSee you for more commandsThe command);
  • aShowDefaultUI: Whether to display the user interface, usually yesfalse;
  • aValueArgument: Some commands require additional arguments, which are generally not used.

compatibility

This method was not very compatible in the past, but it is now compatible with all major browsers and can also be used on mobile devices.

use

Copy from the input box

Now that we have an tag on the page, and we want to copy the content, we can do this:

<input id="demoInput" value="hello world">
<button id="btn">Let me copy</button>
Copy the code
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 successful'); }})Copy the code

Copy it elsewhere

Sometimes there is no tag on the page, and we may need to copy the content from a

, or copy the variables directly.

Remember from the definition of the execCommand() method that it can only operate on editable areas, which means that it is not available except for input fields such as and

This is when we need to save the country.

<button id="btn">Let me copy</button>
Copy the code
const btn = document.querySelector('#btn');
btn.addEventListener('click', () = > {const input = document.createElement('input');
	document.body.appendChild(input);
 	input.setAttribute('value'.'I hear you want to copy me.');
	input.select();
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('Copy successful');
	}
    document.body.removeChild(input);
})
Copy the code

It’s like the curve saved the country. When using this method, several pits were encountered.

In the pit of

When debugging in Chrome, this method works perfectly. Then when it comes to mobile debugging, the pit comes out.

Yes, that’s right, you, ios…

  1. Click copy at the bottom of the screen will appear white screen shake, carefully see is to pull up the keyboard and instantly put away

    Knowing what causes the jitter is easier to solve. Now that you’re pulling up the keyboard, you’re focusing on the input field, so just make the input field incontestable by adding input.setAttribute(‘readonly’, ‘readonly’); Make this read only, so you don’t pull up the keyboard.

  2. Unable to copy

    This problem is because input.select() does not select all content in ios, we need to use another method to select content, this method is input.setSelectionRange(0, input.value.length); .

The complete code is as follows:

const btn = document.querySelector('#btn');
btn.addEventListener('click', () = > {const input = document.createElement('input');
    input.setAttribute('readonly'.'readonly');
    input.setAttribute('value'.'hello world');
    document.body.appendChild(input);
	input.setSelectionRange(0.9999);
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('Copy successful');
	}
    document.body.removeChild(input);
})
Copy the code

conclusion

That’s how JavaScript works to copy content to the clipboard, with a few links:

execCommand MDN

ExecCommand compatibility

clipboard.js