Demand background

Users often need to select all the data on some pages and then copy the work, users generally need two steps, the first step is to select the text, the user can click three times or drag the mouse after the click to select, the second step is to right click and choose copy, or use the keyboard shortcut. In order to improve the user experience, we want the user to click on the relevant text, automatically select all and complete the copy operation.

1. Implementation scheme of text full selection

1.1 Using the CSS User-select attribute

The CSS attribute user-select controls whether a user can select text

auto | text | none | contain | all

Contain user-selet: all contains a user-selet: all feature that contains all text.

Advantages: Can be very flexible, and very simple, a statement can complete the function.

Disadvantages: As an optimization requirement, you need to modify the original code. If you want to add this functionality to an already written page, you need to find each specific location and then add the corresponding className or add the CSS interline style.

1.2 Use Javascript cursor object selection

Selection represents the currently active selection area, that is, blocks of highlighted text, and/or other elements in the document where the user can perform some action.

export default() = > {// Listen for the mouse click event
  document.addEventListener('click'.(e: Event) = > {
    // Get the dom element for the mouse click
    const span = e.target;
    // Get the innerText value of the DOM element
    const value = (span as HTMLElement).innerText;
    // Iterate over all configured regular expressions
    for (const reg of Object.values(regObject)) {
      if (reg.test(value)) {
        // Verify that the reged-in value is a SPAN or div element, because you don't want to have this function in the input field
        if ((span as HTMLElement).localName === ('span' || 'div')) {
          // Get a Selection object
          const selection = window.getSelection();
          // Clear the selection firstselection? .removeAllRanges();// Create a range object
          const range = document.createRange();
          // Make the range object contain the contents of a node
          range.selectNodeContents(span as HTMLElement);
          // Add a range to selectionselection? .addRange(range); }}}}); };Copy the code

Ideas for the realization of the technical scheme:

  1. Listen for mouse click events
  2. Define a regular matching rule for the text, for example, in this requirement to select all Location IDS, the re is/ ^ {3} [a-z] - [a-z] (- [0-9] {1, 2}) + $/, the symbol used in this regular expression means:

^ Indicates (out-of-character) matching at the beginning of A line, in multi-line matching matching at the beginning of A line [a-z] is equivalent to all uppercase letters {m} is equivalent to {m,m}, occurs m times [0-9] is equivalent to all numbers {1,2} is equivalent to one or two occurrences of the preceding content + is equivalent to {1,}, The $(dollar sign) match end occurs at least once, matching the end of a line in a multi-line match

  1. If the text passes the regex check, then the element type is determined. In this example, you only want the text in div and SPAN elements, so you use the localName attribute to determine the element type
  2. After a series of validations, we get the Selection object and use removeAllRanges to empty the contents (equivalent to initialization)
  3. Then get the range object through createRange and use the selectNodeContents of the Range object to get the range
  4. Finally, use addRange to highlight the text message

Advantage: app. vue entry file can be added at a time, no need to modify the original code

Disadvantages: The data that needs to be highlighted needs to have certain structural characteristics, such as rules for the data. Also, adding a global click listening event adds a bit of performance overhead

Text full selection implementation scheme summary

Both schemes have their advantages and disadvantages. It is necessary to select an appropriate scheme based on specific scenarios and requirements. This paper only provides a reference for one way of thinking.

2. Automatic replication implementation scheme

There are three ways to automatically copy content to the clipboard:

  • Document. ExecCommand () method
  • Asynchronous Clipboard API
  • Copy event and Paste event

2.1 Document. ExecCommand () method

Document.execcommand () is a traditional way to manipulate the clipboard, supported by all browsers.

It supports copy, cut, and paste.

ExecCommand (‘paste’) execCommand(‘paste’)

The drawback of the document.execcommand () method is that it can only copy the contents of the highlighted text, it can’t customize the information into the clipboard, and it only supports synchronous operations. But for our needs, this approach is sufficient.

2.2 Asynchronous Clipboard API

All operations on the Clipboard object are asynchronous, return Promise objects, and do not cause the page to stall.

const clipboardObj = navigator.clipboard;

Moreover, it can put any content (such as pictures) into the clipboard. There are four methods:

The clipboard.readText () method is used to copy text data from the Clipboard. The clipboard.read () method is used to copy data from the Clipboard, which can be either text or binary data. Clipboard.writetext () is used to write text to the Clipboard. It can be text data or binary data

This operation is more flexible and efficient. However, the disadvantage is that Chrome stipulates that only PAGES using HTTPS protocol can use this API, but our project is not using this protocol, so we cannot use this API.

2.3 copy the event

This method requires first triggering a copy operation using the document.execcommand (‘copy’) method in 2.1, and then listening for copy.

    document.addEventListener('copy'.async (e) => {
      e.preventDefault();
      try {
        let clipText = ' '.// Put the custom content into the clipboard
        e.clipboardData.setData('text/plain', clipText)
      } catch (err) {
        console.log(err); }});Copy the code

This requirement is not an application scenario for this approach, which can be used as follows:

Use this method when you want to customize something to the clipboard, but your project doesn’t use the HTTPS protocol. Note, however, that since the 2.1 document.execcommand () method is synchronous only, calling from an asynchronous operation is useless. If you want to put something in the clipboard that needs to be requested asynchronously, then calling the copy operation directly after the request will not work. Here’s a code example:

async getData () {
  try {
    await this.getClipboardData();
    // The copy operation triggered here is invalid
    document.execCommand("Copy")}}Copy the code

So the interaction needs to be, save the data that comes back asynchronously, wait for the data to come back, and then, with a button or some other way, synchronize the replication operation.

Summary of implementation scheme of automatic trigger replication

All three methods have their own applications, but the third copy event method will pollute the actual copy operation and is not recommended as a bottom-saving solution.

reference

MDN: User-select MDN: Selection MDN: Document.createrange () JS regular expression complete tutorial javascript to implement mouse click automatically select click elements within the text