Home > Web Front-end > JS Tutorial > How to Read the Clipboard Content on Page Load Using the Clipboard API?

How to Read the Clipboard Content on Page Load Using the Clipboard API?

Susan Sarandon
Release: 2024-10-27 13:30:02
Original
930 people have browsed it

How to Read the Clipboard Content on Page Load Using the Clipboard API?

How to Retrieve Clipboard Content on Page Load

Web browsers provide an API for accessing the clipboard, enabling you to retrieve its content on page load without user interaction. This feature is particularly useful for tasks like pre-populating text fields or displaying clipboard data.

Using the Clipboard API

The Clipboard API (navigator.clipboard) provides a method called readText(). As the name suggests, it allows you to read the current text content from the clipboard.

You can use this API in two ways: with asynchronous/await syntax or Promise syntax.

With Async/Await Syntax:

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

With Promise Syntax:

<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

It's important to note that this API prompts the user with a permission request dialog box. This ensures that no malicious scripts can access clipboard data without user consent.

Limitations and Workarounds

The Clipboard API does not work in Firefox as of version 109. If you need to support Firefox users, you can consider using a third-party clipboard library.

To run the API code from the console, you can use a timeout and quickly click in the website window.

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

Additional Resources

For more information and usage guidelines, refer to the following Google developer documentation:

  • [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API)
  • [Spec](https://w3c.github.io/clipboard-apis/)

The above is the detailed content of How to Read the Clipboard Content on Page Load Using the 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