Home > Web Front-end > JS Tutorial > How Can I Efficiently Copy Text to the Clipboard Using JavaScript?

How Can I Efficiently Copy Text to the Clipboard Using JavaScript?

Barbara Streisand
Release: 2024-12-29 20:48:17
Original
618 people have browsed it

How Can I Efficiently Copy Text to the Clipboard Using JavaScript?

How to Copy to the Clipboard in JavaScript

In JavaScript, there are multiple ways to copy text to the clipboard, depending on the browser support.

1. Async Clipboard API [navigator.clipboard.writeText]

Available in Chrome 66, the Async Clipboard API offers asynchronous access to the clipboard. It uses JavaScript Promises, allowing seamless execution without user prompts interrupting the page. Additionally, text can be directly copied to the clipboard from a variable. Note that it only works on pages served over HTTPS.

2. document.execCommand('copy') (Deprecated)

This method is synchronous and supported by most browsers since April 2015. It stops JavaScript execution until the process is complete, potentially displaying security prompts to the user. Text is copied from the DOM to the clipboard.

General Development Notes:

  • Clipboard commands may not work while testing code in the console.
  • Pages must be active (for Async Clipboard API) or require user interaction (for document.execCommand('copy')) to access the clipboard.

Fallback Method:

To ensure cross-browser compatibility, it's recommended to use a fallback method alongside the Async Clipboard API. Here's an example:

function fallbackCopyTextToClipboard(text) {
  // Create a textarea element and copy text to it
  const textArea = document.createElement("textarea");
  textArea.value = text;

  // Append the textarea to the body and set properties
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  // Execute the copy command
  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Fallback: Copying text command was ' + msg);
  } catch (err) {
    console.error('Fallback: Oops, unable to copy', err);
  }

  // Remove the textarea from the body
  document.body.removeChild(textArea);
}

function copyTextToClipboard(text) {
  if (!navigator.clipboard) {
    fallbackCopyTextToClipboard(text);
    return;
  }
  navigator.clipboard.writeText(text).then(function() {
    console.log('Async: Copying to clipboard was successful!');
  }, function(err) {
    console.error('Async: Could not copy text: ', err);
  });
}
Copy after login

The above is the detailed content of How Can I Efficiently Copy Text to the Clipboard Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template