Open In App

Web API Clipboard

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Web API Clipboard is a powerful feature that allows web developers to interact with the user’s clipboard directly from a web application.

Concept and Usage

The Web API Clipboard provides a standardized way to interact with the user’s clipboard through JavaScript. It allows developers to perform the following key operations:

  • Copy: Programmatically copy text or data to the clipboard.
  • Cut: Cut selected text or data from a web page and copy it to the clipboard.
  • Paste: Paste data from the clipboard into a web application.

Interfaces

  • Clipboard: Represents the clipboard in a read-write manner. The Clipboard interface is at the core of clipboard interactions. It allows you to access and manipulate clipboard data.
  • ClipboardEvent: Provides access to clipboard data during clipboard events(cut, copy, paste). The ClipboardEvent interface is essential for handling clipboard-related events and managing data transfer between the clipboard and your web application.
  • ClipboardItem: It is used for representing a single item format and reading and writing data.

Web API Clipboard Methods

Two fundamental methods of the Web API Clipboard are:

  • writeText(text): Writes the specified text to the clipboard. This method is used to copy text to the clipboard. It accepts the text you want to copy as a parameter.
  • readText(): Reads text from the clipboard. This method allows you to retrieve text from the clipboard and use it in your web application.

Example 1: This example shows the use of the writeText() method.

Javascript




navigator.clipboard.writeText('Hello, Web Clipboard!')
    .then(() => {
console.log('Text copied to clipboard');
})
    .catch(err => {
console.error('Unable to copy text: ', err);
});


Example 2: This example shows the use of the readText() method.

Javascript




navigator.clipboard.readText()
    .then(pastedText => {
console.log('Pasted text: ', pastedText);
})
    .catch(err => {
console.error('Unable to paste text: ', err);
});


Browser Support

  • Chrome
  • Firefox
  • Safari
  • Edge


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads