Two common methods for copying content from JavaScript to the clipboard: javascript clipboard

Source: Internet
Author: User

Two common methods for copying content from JavaScript to the clipboard: javascript clipboard

Common Methods

I checked the omnipotent Google. The common methods are as follows:

Third-party Library: clipboard. js
Native method: document.exe cCommand ()

Let's take a look at how these two methods are used.

Clipboard. js

This is the official website of clipboard: https://clipboardjs.com.

Reference

Direct reference:

<Script src = "dist/clipboard. min. js"> </script>

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

Use

Copy from input box
Now there is a <input> label 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"> click Copy </button>
import Clipboard from 'clipboard';const btnCopy = new Clipboard('btn');

Note that<button>Addeddata-clipboard-target Attribute. Its value must be copied. <input>OfidAs the name suggests, the content is copied from the entire tag.

Direct Replication

Sometimes, we do not want to copy the content from <input>, but simply take the value directly from the variable. In Vue, we can do this:

<Button class = "btn": data-clipboard-text = "copyValue"> click Copy </button>

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

Event

Sometimes we need to do something after the replication, and at this time we need the support of the callback function.

Add the following code to the handler:

// The clipboard callback function executed after the copy is successful. 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 ('triggers: ', e. trigger); // trigger element: for example, <button class = "btn": data-clipboard-text = "copyValue"> click I copy </button> e. clearSelection (); // clear selected content}); // The callback function clipboard executed after the replication fails. on ('error', function (e) {console. error ('Action: ', e. action); console. error ('triggers: ', e. trigger );});

Summary

This document also mentions that if you useclipboardTo make lifecycle management more elegant, rememberbtn.destroy() Destroy it.

Clipboard is easy to use. However, is it not elegant to use additional third-party libraries for a copy function? What should I do at this time? Use the native method to implement it.

Document.exe cCommand () method

First, let's take a look at this method inMDNOn how to define:

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

This means that you can run commands to operate the content of the Editable area. Note that the Editable area is used.

Definition

Bool = document.exe cCommand (aCommandName, ashowdefaui UI, aValueArgument)

Method returns a Boolean value, indicating whether the operation is successful.

  • ACommandName: indicates the command name, such as copy and cut. For more commands, see commands );
  • Ashowdefaui UI: whether to display the user interface, which is generally false;
  • AValueArgument: Some commands require additional parameters, which are generally not used;

Compatibility

This method is not compatible with the previous version, but it is now basically compatible with all mainstream browsers and can be used on mobile terminals.

Use

Copy from input box
Now there is a <input> label on the page. to copy the content, we can do this:

<Input id = "demoInput" value = "hello world"> <button id = "btn"> click Copy </button>

Js Code

Const btn = document. querySelector ('# btn'); btn. addEventListener ('click', () => {const input = document. querySelector ('# demoinput'); input. select (); if (document.exe cCommand ('copy') Then document.exe cCommand ('copy'); console. log ('copied successfully ');}})

Copy elsewhere

Sometimes there is no<input>Tag, we may need<div>Or directly copy the variable.

RememberexecCommand() As mentioned in the definition of a method, it can only operate editable areas, that is, it means that this method cannot be used except for input fields such as <input> and <textarea>.

At this time, we need to save the country.

<Button id = "btn"> click Copy </button>

Js Code

Const btn = document. querySelector ('# btn'); btn. addEventListener ('click', () => {const input = document. createElement ('input'); document. body. appendChild (input); input. setAttribute ('value', 'heard you want to copy me'); input. select (); if (document.exe cCommand ('copy') Then document.exe cCommand ('copy'); console. log ('copied successfully');} document. body. removeChild (input );})

It is a success in saving the nation. When I used this method, I encountered several pitfalls.

Pitfalls

This method works perfectly during Chrome debugging. Then, when debugging is performed on the Mobile End, the fault is thrown out.

Yes, that's right. It's you, ios...

1. When you click Copy, white screen jitter will appear at the bottom of the screen.

It is better to know what causes the jitter. Since the keyboard is pulled up, it is focused on the input field, as long as the input field is not input, just add input in the code. setAttribute ('readonly', 'readonly'); if this <input> is read-only, the keyboard will not be pulled.

2. Unable to copy

This problem is caused by input. select () does not select all content in ios. We need to use another method to select the 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.exe cCommand ('copy') Then document.exe cCommand ('copy'); console. log ('copied successfully');} document. body. removeChild (input );})

Summary

The above section describes how to copy content to the clipboard in JavaScript, and attaches several links:

ExecCommand MDN

ExecCommand compatibility

Clipboard. js

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.