Home > Web Front-end > JS Tutorial > body text

How to Retrieve Clipboard Content with the JavaScript Clipboard API?

Patricia Arquette
Release: 2024-10-27 11:16:29
Original
998 people have browsed it

How to Retrieve Clipboard Content with the JavaScript Clipboard API?

Clipboard Retrieval in JavaScript

Detecting the contents of the clipboard and automatically pasting it into a text field is a common task in JavaScript applications. This guide demonstrates a solution using the modern Clipboard API.

Solution

To retrieve the clipboard content, use the navigator.clipboard.readText() method. This API is supported in most modern browsers, except Firefox 109 and later. The syntax for async/await is as follows:

<code class="javascript">const text = await navigator.clipboard.readText();</code>
Copy after login

For Promise syntax, use:

<code class="javascript">navigator.clipboard.readText()
  .then(text => {
    console.log('Pasted content: ', text);
  })
  .catch(err => {
    console.error('Failed to read clipboard contents: ', err);
  });</code>
Copy after login

Permission Request

Note that the readText() method requires user permission. Users will see a dialog box requesting permission to access their clipboard. Ensure that your application handles this permission request appropriately.

Console Execution

This solution will not work if called from the console directly. You can set a timeout to run the code once a browser window is active:

<code class="javascript">setTimeout(async () => {
  const text = await navigator.clipboard.readText();
  console.log(text);
}, 2000);</code>
Copy after login

Additional Resources

For more details on the Clipboard API, refer to the following resources:

  • [Google Developer Docs](https://developers.google.com/web/updates/2018/03/clipboardapi)
  • [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard)

The above is the detailed content of How to Retrieve Clipboard Content with the JavaScript Clipboard API?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!