Connect with us

Technology

Tips on how to Reduce, Copy and Paste on the Internet with the Clipboard API – SitePoint


Accessing the OS clipboard utilizing browser JavaScript has been potential for a number of years utilizing doc.execCommand().

Sadly, there are some issues:

  • clipboard entry is synchronous, which has efficiency and safety implications
  • help is patchy, particularly on older variations of Safari on macOS and iOS
  • permissions entry varies throughout browsers, and
  • the API might by no means be thought of elegant

It’s lastly been outmoded by a brand new asynchronous Clipboard API. It’s new, and no browser helps all options, however it’s simpler to make use of and extra sturdy.

Why Would an App Have to Entry the Clipboard?

As a developer, you’ll understand how the clipboard works and often use the next keyboard shortcuts:

  • Ctrl | Cmd + C to repeat
  • Ctrl | Cmd + X to chop
  • Ctrl | Cmd + V to stick

These with much less computing expertise received’t essentially have that data. They could even be utilizing a touch-screen system the place keyboard shortcuts aren’t out there. Providing easy-to-use reduce and paste icons may be helpful.

Moreover, you might wish to modify content material when a clipboard motion is accomplished, akin to including or eradicating formatting.

Clipboard Entry is Harmful!

Accessing the clipboard programmatically raises a number of safety issues:

  • Customers typically copy passwords or personal data so no web page ought to have the ability to arbitrarily learn clipboard information.
  • Pages needs to be restricted when including information to the clipboard. A nefarious web page might change copied textual content with a harmful command and even an executable file.

To keep away from potential points, the Clipboard API can solely be used on pages served over HTTPS (localhost can also be permitted). When operating in an iframe, the mother or father web page should additionally grant clipboard-read and/or clipboard-write permissions:

<iframe
  src="childpage.html"
  permit="clipboard-read; clipboard-write"
></iframe>

The API is simply out there to the energetic browser tab (not background tabs) and may solely be triggered by a person interplay akin to a click on. When mandatory, the person shall be prompted for permission to learn clipboard information:

This alert is proven when a web page first requests clipboard entry. It shouldn’t trigger any points, on condition that the API is asynchronous and returns a Promise. It’s additionally potential to look at and request the standing utilizing the Permissions API.

Clipboard API Function Detection

The Clipboard API is out there when navigator.clipboard returns a truthy outcome. For instance:

if (navigator.clipboard) {

  console.log('Clipboard API out there');

}

Nevertheless, this doesn’t assure the browser helps all options, so it’s essential to make additional checks. For instance, on the time of writing, Chrome helps the API’s readText() technique, whereas Firefox doesn’t.

Copy and Paste Textual content

Copying and pasting textual content shall be a helpful choice in most purposes. The API is refreshingly easy:


await navigator.clipboard.writeText('This textual content is now within the clipboard');


let textual content = await navigator.clipboard.readText();

You’ll require significantly extra code to detect help and deal with errors …

View the Clipboard API textual content demonstration

The code may be downloaded from GitHub. Discuss with clipboardtext.js for the JavaScript.

This instance implements textual content copying when a data-copy attribute is added any HTML factor akin to a button. You may set this worth to both of those:

  1. a hard-coded string — akin to data-copy="copy this to the clipboard".
  2. a CSS selector — akin to data-copy="#mysection". The textual content content material of the primary matching factor is then copied.

Optionally, you’ll be able to set a customized success message in a data-done attribute:

<button data-copy="#mysection" data-done="part copied">
  copy textual content from #mysection
</button>

The button is simply proven when navigator.clipboard.writeText() is supported. When clicked, the JavaScript occasion handler locates the textual content, copies it to the clipboard, and exhibits an animated success message.

The textual content paste button may be very related besides it defines a data-paste attribute which should level to a DOM node:

<textarea id="pastehere"></textarea>
<button data-paste="#pastehere">paste</button>

Copy and Paste Information

The Clipboard API’s readText() and writeText() are comfort choices for the extra generic learn() and write() strategies. These have much less browser help however are in a position to copy and paste any kind of knowledge akin to binary pictures.

Copying requires blob information usually returned by a fetch() or canvas.toBlob() technique. That is handed to a ClipboardItem constructor so it may be written to the clipboard:

const
  picture = await fetch('myimage.png'),
  blob = await picture.blob();

await navigator.clipboard.write([
  new ClipboardItem({ [blob.type]: blob })
]);

Pasting is extra advanced as a result of a number of ClipboardItem objects may be returned with differing content material varieties. It’s subsequently essential to iterate by means of every kind till a helpful format is discovered. For instance:

const clipboardItems = await navigator.clipboard.learn();

for (const clipboardItem of clipboardItems) {

  for (const kind of clipboardItem.varieties) {

    if (kind === 'picture/png') {

      
      return await clipboardItem.getType(kind);

    }

  }

}

View the Clipboard API picture demonstration (supported in Chromium-based browsers).

The code may be downloaded from GitHub. Discuss with clipboardtext.js for the JavaScript.

This works in the same method to the textual content demonstration, in that replicate and paste buttons should level to DOM components utilizing a CSS selector in data-copyblob and data-pasteblob attributes. For instance:


<img id="myimage" src="myimage.png" alt="any picture" />

<button data-copyblob="#myimage" data-done="picture copied">
  copy picture
</button>


<div id="imagelist"></div>

<button data-pasteblob="#imagelist">
  paste picture
</button>

Strive copying picture information from a graphics utility, then use the paste button.

Reduce, Copy, and Paste Occasions

The reduce, copy, and paste occasions hearth at any time when the person initiates a clipboard motion within the browser — usually with right-click menus or the keyboard shortcuts talked about above. That is supported in most browsers and handler features can intercept the occasions to make adjustments utilizing a clipboardData object handed as a parameter.

The next perform forces all reduce or copied textual content to be uppercase. Be aware that e.preventDefault() stops the default reduce/copy motion which might override it:

physique.addEventListener('reduce', cutCopyHandler);
physique.addEventListener('copy', cutCopyHandler);


perform cutCopyHandler(e) {

  const choice = doc.getSelection();

  
  e.clipboardData.setData(
    'textual content/plain',
    choice.toString().toUpperCase()
  );

  if (e.kind === 'reduce') choice.deleteFromDocument();

  
  e.preventDefault();

}

The next code attaches a paste handler to a particular <textarea> subject. The perform clears the present content material and prefixes the textual content "pasted:":

doc.getElementById('field1').addEventListener('paste', pasteEvent);


perform pasteEvent(e) 

View the Clipboard API occasion demonstration

The code may be downloaded from GitHub. Discuss with clipboardtext.js for the JavaScript.

Prepared for Use?

The Clipboard API is new however has affordable browser help and feels extra sturdy than the previous doc.execCommand() choice.

It’s greatest added as a progressive enhancement so reduce, copy, and paste performance is simply applied in your utility when the power is out there. Please use the code supplied right here if you need a head begin.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *