In recent Web development, there have been scenarios using Clipboard. That is, the copy and paste function is required for complex page configurations in the B Web service. Several schemes were considered:

  • From the perspective of requirements, a relatively simple solution is to call the background interface to generate a new data, and users can modify the new data. This method works for copy and paste in the same environment (product or Devnet).

  • Front-end localStorage: detecting when adding a new operation when a user triggers replication, data is saved to the local localStorage. When a user adds a new operation, detecting whether data has been replicated in the localStorage. Because the front-end retains the copied data, you can use copy-paste between the test environment and the live network environment without considering the environment problems in the background. However, the switch between the test environment and the live network environment depends on the proxy configuration. Xxx.xx.com or test.xxx.xx.com. For applications whose environments are distinguished by different domain names, localStorage cannot read data across domains because it is restricted by the same-origin policy.

  • Using Clipboard on the basis of the front-end local storage scheme, came up with the Clipboard scheme. Similar to password scouring, data is stored in Clipboard, and then when new data is added, the Clipboard can be detected. Using Clipboard takes advantage of the system’s data storage and also resolves cross-domain issues between different domain names.

The changes to the Clipboard

document.execCommand

Docment. execCommand is a synchronous method that manipulates areas of editable content.

/ / grammar
bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument);
Copy the code

ACommandName, the first parameter of the aCommandName method, is passed in as the command word, including the operations copy, cut, bold, backColor, and so on. The second parameter to the method, aShowDefaultUI, indicates whether to display the user interface. This parameter is generally not used. The third parameter to the method, aValueArgument, is some additional parameter to pass in the action command. The method returns a bool describing whether the operation was successful. Refer to MDN for details

What we need to do is write the required content to the Clipboard, using the copy mentioned above

So without further ado, let’s go through the code and see how we can use this, okay

<div>
    <input type="text" value="Copy Content"/>
    <button onclick="handleClick">copy</button>
</div>
Copy the code
const i = document.querySelector('input');
// Get focus
i.select();
document.execCommand('copy');
Copy the code

Click the button, Copy Content is written to the clipboard, and you can Copy and paste the clipboard Content somewhere else.

At this point, you might wonder, “Why use an input component?” Of course, you can also use a textarea. As mentioned above, only input, Textarea, or elements with contenteditable attributes can be manipulated by execCommand

So what can you do if you don’t want editable areas on your page?

/** * @description copy content to clipboard * @param {string} content Text content */
function copy2Clipboard = content= >{

  const dom = document.createElement('input');
  dom.value = content;
  document.body.appendChild(dom);
  dom.select();
  document.execCommand('copy');

  document.body.removeChild(dom);
};
Copy the code

You can use the above trick method

navigator.clipboard.writeText

The above document. ExecCommand is a synchronous operation. Navigator. clipboard is a clipboard API provided by the browser, through which clipboard operation can be implemented. Major browser vendors have also recently supported the Navigator.Clipboard API.

So how do you use it? Let’s start with the code.

navigator.permissions.query({ name: 'clipboard-write' }).then(function(result) {
    // may be 'granted', 'denied' or 'prompt':
    if (result.state === 'granted') {
        // You can use the permission
        // Perform clipboard operations
        navigator.clipboard.writeText('Clip Content').then(
            function() {
                /* clipboard successfully set */
                // The clipboard was set successfully
            },
            function() {
                /* clipboard write failed */
                // Failed to write clipboard content}); }else if (result.state === 'prompt') {
        // Pop-up box to apply for permission
    } else {
        // If rejected, do nothing.}});Copy the code

Navigator.permissions is an API for the browser to request the user to use the sensitive interface, which will Prompt the user to ask whether the user can use the relevant permissions. The above code first queries the permission of the clipboard-write request. After the permission by calling the navigator. Clipboard. WriteText method.

Navigator. clipboardAPI is intended to replace the Document. execCommand interface, so it is also recommended to use the clipboardAPI for copying operations.

The code is as follows:

async function copy2Clipboard(content) {
    const res = await navigator.permissions.query({ name: 'clipboard-write' });
    if (res.state === 'granted') {
        return navigator.clipboard.writeText(content);
    }

    return Promise.reject(res);
}
Copy the code

Pay attention to [IVWEB community] public number to check the latest technology weekly, do better yourself!


The Clipboard is read

document.execCommand

For security reasons, the document.execCommand(‘paste’) operation has been disabled.

So what’s a way to read the clipboard?

Listen for paste events

document.addEventListener('paste', event => {
    // Read clipboardData from event
    const pasteContent = (event.clipboardData || window.clipboardData).getData('text');
    // do whatever
});
Copy the code

In this requirement scenario, you want clipboard content that can be read by the front end rather than triggered by the user, so I won’t go into details here.

So what’s the alternative?

navigator.clipboard.readText

The navigator. Clipboard. ReadText is also a browser clipboard operation API, like writeText, also need to request a clipboard.

// Apply for clipboard read permission
navigator.permissions.query({ name: 'clipboard-read' }).then(function(result) {
    // may be 'granted', 'denied' or 'prompt':
    if (result.state === 'granted') {
        // You can use the permission
        // Perform clipboard operations
        navigator.clipboard
            .readText()
            .then(text= > {
                console.log('Copy and paste text:', text);
            })
            .catch(err= > {
                // Failed to read clipboard contents
                console.error('Failed to read clipboard contents: ', err);
            });
    } else if (result.state === 'prompt') {
        // Pop-up box to apply for permission
    } else {
        // If rejected, do nothing.}});Copy the code

First of all we want to apply for to use clipboard clipboard – read permissions, after the user permissions, you can through the navigator. Clipboard. ReadText access permissions.

It is also possible to listen for paste events

document.addEventListener('paste', event => {
    event.preventDefault();
    navigator.clipboard.readText().then(text= > {
        console.log('Pasted text: ', text);
    });
});
Copy the code

Thus, we can abstract away the ability to read the contents of the clipboard:

/** * @description reads the clipboard contents * @return {string} */
async function readClipboard() {
    const result = await navigator.permissions.query({ name: 'clipboard-read' });
    if (result.state === 'granted' || result.state === 'prompt') {
        return navigator.clipboard
            .readText()
            .then(text= > text)
            .catch(err= > Promise.reject(err));
    }
    return Promise.reject(result);
}
Copy the code

Summary and Attention

Clear clipboard contents

The browser does not provide an interface to clean up the clipboard. If a site needs to clean up after using clipboard content, it can write data again

// ...
input.value = ' '; // The input value must have a value, not an empty string
input.select();
document.execCommand('copy')
// Or use clipboard
navigator.clipboard.writeText(' ');
Copy the code

Security issues

Manipulating clipboard content on the Web has certain security risks. To ensure user privacy, browsers require navigator. ClipboardAPI to be connected to HTTPS.

HTTP sites do not support this interface, only document.execCommand(‘copy’) and listen for paste events

From the user’s point of view, it is also recommended that everyone’s website access HTTPS

The future of the clipboard

More general write and read methods may be supported, providing for writing binary data, etc. (images, etc.).

reference

Unblocking Clipboard Access

Cut and Copy Commands