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
Linda HamiltonOriginal
2024-12-26 20:57:15164browse

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);
  // ...
}

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!

Statement:
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