Home >Web Front-end >JS Tutorial >How to Retrieve Clipboard Content with the JavaScript Clipboard API?

How to Retrieve Clipboard Content with the JavaScript Clipboard API?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 11:16:291095browse

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>

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>

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>

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!

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