Clipboards are used frequently on productivity platforms. The Clipboard API has also gained popularity among major browsers. Productivity tools based on front-end technologies need to consider the ability to access these.

Roughwin. Making. IO/clipboard – d…

Technically possible scenarios are:

  • Read the clipboard contents in the onPaste event
  • In the onCopy event, you can block default behavior, write custom data to the clipboard…
  • Clipboard writes can be performed by JS programs in events such as onClick

These technical scenarios can support business scenarios such as:

  • Pasting Word text to a page (plain Text, HTML, RTF, etc.)
  • Paste images, audio and video files into web pages
  • When users copy text, add a copyright notice
  • Prohibit users from copying text and checking the replication behavior
  • Click the button to copy the data to the clipboard
  • Copy the react component’s state to another component

Let’s look at the implementation

Copy external resources to the browser

In the browser’s onpaste event, you can retrieve a DataTransfer type field, Event.clipboardData. It allows you to get information about resources pasted into the browser. We encapsulate this process as a general function.

function readDataTransferItemAsString(item) {
  return new Promise(function (resolve) { item.getAsString(resolve); })}async function getClipboardData(data) {
  const { items } = data;
  const result = {};
  await Promise.all([...items].map(async item => {
    console.log(item)
    const { type, kind } = item;
    if (kind === 'string') {
      result[type] = await readDataTransferItemAsString(item);
    } else if (kind === 'file') { result[type] = item.getAsFile(); }}))console.log(result)
  return result;
}
function handlePaste(e) {
  getClipboardData(e.clipboardData).then(setClipInfo)
}

document.removeEventListener('paste', handlePaste);
Copy the code

Copy a text from OneNote to the browser:

As you can see, the pasted information includes text/plain, text/ HTML, text/ RTF, and image/ PNG formats. You can use the pasted information according to your service requirements.

Prevents and replaces the default behavior of the browser

Sometimes we want to protect page content from being copied. You can listen for onCopy events on document. Such as:

function handleCopy(e) {
  e.preventDefault()
  const { clipboardData } = e
  clipboardData.clearData();
  clipboardData.setData('text/plain'.'In Copyright')}document.addEventListener('copy', handleCopy)
Copy the code

When we select text on the page and copy it:

The default behavior has been overwritten, and the stickboard has been emptied and filled with the text we’ve set up.

Click on the button to copy

function handleClick(e) {
  function handleCopy(e) {
    e.preventDefault()
    const { clipboardData } = e
    clipboardData.clearData();
    const msg = `code: The ${Math.random().toString().slice(2.10)}\ncopied at: The ${new Date().toISOString()}`;
    clipboardData.setData('text/plain', msg);
    document.removeEventListener('copy', handleCopy);
    setResult(msg)
  }
  document.addEventListener('copy', handleCopy)
  document.execCommand('copy');
}
Copy the code

Clicking the button in Demo2 automatically writes a text to the clipboard

Note: the document. ExecCommand (‘ copy ‘); This action only works within a specific event response function, such as onClick.

Copy the state of one component to another

I wrote two React components that encapsulate the clipboard-related state logic as useClipboardData:

import { useState, useEffect } from 'react';

function readDataTransferItemAsString(item) {
  return new Promise(function (resolve) { item.getAsString(resolve); })}async function getClipboardData(data) {
  const { items } = data;
  const result = {};
  await Promise.all([...items].map(async item => {
    console.log(item)
    const { type, kind } = item;
    if (kind === 'string') {
      result[type] = await readDataTransferItemAsString(item);
    } else if (kind === 'file') { result[type] = item.getAsFile(); }}))console.log(result)
  return result;
}

export function useClipboardState(initData) {
  const [data, setData] = useState(initData);
  useEffect(function () {
    async function handlePaste(e) {
      const d = await getClipboardData(e.clipboardData);
      if (d && d['text/custom']) {
        try {
          setData(JSON.parse(d['text/custom'))}catch (e) {
          console.log('paste failed.')}}}function handleCopy(e) {
      e.preventDefault()
      const { clipboardData } = e
      clipboardData.clearData();
      clipboardData.setData('text/custom'.JSON.stringify(data))
    }
    document.addEventListener('copy', handleCopy)
    document.addEventListener('paste', handlePaste);
    return function () {
      document.removeEventListener('paste', handlePaste);
      document.removeEventListener('copy', handleCopy)
    }
  }, [data]);
  return [data, setData]
}
Copy the code

On the Demo3 page, press Ctrl+C to copy its state to the clipboard, and on the Demo4 page, press Ctrl+V to paste. In addition, serialized status information can be sent by email or chat box. This interactive logic can greatly facilitate user operation.

The last

So that’s my summary of a few clipboard API scenarios. These apis have been put into use in the projects I am in charge of (rich text editing, paper typesetting system), and have been well received by users. Those who need it can refer to it.