get clipboard value then get object promise and show in an alert in javascript

To get the clipboard value in JavaScript, you can use the navigator.clipboard.readText() method which returns a promise that resolves to the text contents of the clipboard. You can then use the JSON.parse() method to convert the text into a JavaScript object.

Here is an example code snippet that demonstrates how to get the clipboard value as an object and show it in an alert:

index.tsx
navigator.clipboard.readText()
  .then(text => {
    const clipboardObject = JSON.parse(text);
    alert(JSON.stringify(clipboardObject));
  })
  .catch(error => {
    console.error('Failed to read clipboard text: ', error);
  });
231 chars
9 lines

In this code, we use the .then() method to handle the promise that is returned by the navigator.clipboard.readText() method. The text parameter in the callback function contains the clipboard value as a string.

We then use the JSON.parse() method to parse the string into a JavaScript object, which we store in the clipboardObject variable. Finally, we use the alert() method to display the object as a string in an alert dialog.

If there is an error reading the clipboard, the .catch() method is called to handle the error.

gistlibby LogSnag