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:
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!