get clipboard value and retrieve from promise in javascript

To get the value from the clipboard, we can use the Clipboard API in JavaScript. It provides the asynchronous Clipboard.readText() method that returns a Promise. We can use the Promise to retrieve the value from the clipboard.

Here is an example code block that demonstrates how to get the clipboard value and retrieve it from the Promise:

index.tsx
// Attach an event listener to the button
document.querySelector('button').addEventListener('click', async () => {

    try {
        const text = await navigator.clipboard.readText(); // Try to get the clipboard text
        console.log('Clipboard text:', text); // Log the text value
    } catch (err) {
        console.error('Failed to read clipboard contents: ', err); // If there is an error, log it to the console
    }
});
430 chars
11 lines

In this example, when the button is clicked, an async function is called. Within the function, we use the navigator.clipboard API and call the readText() method. We then use the await keyword to wait for the Promise to resolve and assign the contents of the clipboard to the text variable. We then log the value of text to the console.

However, if there is an error returned by the Promise, we log it to the console using console.error().

gistlibby LogSnag