Home > Web Front-end > JS Tutorial > How Do I Copy Text to the Clipboard in JavaScript Across All Browsers?

How Do I Copy Text to the Clipboard in JavaScript Across All Browsers?

Susan Sarandon
Release: 2024-12-28 07:18:53
Original
368 people have browsed it

How Do I Copy Text to the Clipboard in JavaScript Across All Browsers?

How to Copy to the Clipboard in JavaScript (Across Browsers)

Overview

To copy text to the clipboard, you can utilize three primary browser APIs:

  1. Async Clipboard API (navigator.clipboard.writeText)
  2. document.execCommand('copy') (deprecated)
  3. Overriding the Copy Event

General Development Considerations

  • Disable clipboard functionality when testing code in the console.
  • Pages must be active (Async Clipboard API) or require user interaction (document.execCommand('copy')) to access the clipboard.

Implementation

Async Fallback

For the best browser coverage, combine the Async Clipboard API with a fallback to document.execCommand('copy'):

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

Clipboard API Comparison

API Features Support
API Features Support
Async Clipboard API Text-focused, asynchronous, supports HTTPS Chrome 66 (March 2018), works in inactive tabs
document.execCommand('copy') Synchronous, reads text from DOM Most browsers (as of April 2015), displays permission prompts
Overriding the Copy Event Can modify clipboard content from any copy event, supports various data formats Not directly related to the question
Async Clipboard API

Text-focused, asynchronous, supports HTTPS Chrome 66 (March 2018), works in inactive tabs
document.execCommand('copy') Synchronous, reads text from DOM Most browsers (as of April 2015), displays permission prompts
Overriding the Copy Event

Can modify clipboard content from any copy event, supports various data formats Not directly related to the question
Note (2020/02/20)Deprecated permissions prevent code snippets from working in some browsers. Use an active webpage served over HTTPS for testing and development.

The above is the detailed content of How Do I Copy Text to the Clipboard in JavaScript Across All Browsers?. 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