Home > Web Front-end > JS Tutorial > How to Efficiently Copy Text to the Clipboard Across Multiple Browsers in JavaScript?

How to Efficiently Copy Text to the Clipboard Across Multiple Browsers in JavaScript?

Linda Hamilton
Release: 2024-12-26 20:57:15
Original
162 people have browsed it

How to Efficiently Copy Text to the Clipboard Across Multiple Browsers in JavaScript?

Copying Text to the Clipboard in JavaScript for Multiple Browsers

Overview: Which API to Use?

To copy text to the clipboard, JavaScript provides three main browser APIs:

  • Async Clipboard API (navigator.clipboard.writeText):

    • Available in Chrome 66
    • Asynchronous and uses Promises
    • Can be written to avoid interrupting user prompts
    • Supported only on HTTPS pages
  • document.execCommand('copy'):

    • Widely supported across browsers
    • Synchronous, halting page execution until complete
    • Reads text from the DOM and places it on the clipboard
  • Overriding the copy event:

    • Allows modification of clipboard content for any copy event
    • Supports multiple data formats, beyond plain text
    • Not directly addressed here

General Development Notes

  • Clipboard commands may not work when testing code in the console.
  • Active pages (for Async Clipboard API) or user interaction (for document.execCommand('copy')) is often required.

Async Fallback Approach

Due to varying browser support, it's advisable to use a fallback method. For example:

function fallbackCopyTextToClipboard(text) {
  // ...
}

function copyTextToClipboard(text) {
  if (!navigator.clipboard) fallbackCopyTextToClipboard(text);
  // ...
}
Copy after login

Demo and Conclusion

To test the code and see it in action, visit this demonstration page. Note that embedded examples may not work due to permissions issues in IFRAMEs.

For full cross-browser compatibility, use the Async Clipboard API when supported and fallback to document.execCommand('copy') otherwise.

The above is the detailed content of How to Efficiently Copy Text to the Clipboard Across Multiple Browsers in 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