In this lesson, we look at how to read and write text to and from a users' clipboard. We can do this using the Clipboard API methods which return Promises.
Duration
2 min
Access
Free
Transcript
Available
In this lesson, we look at how to read and write text to and from a users' clipboard. We can do this using the Clipboard API methods which return Promises.
Jhey Tompkins: On our page we have two inputs and two buttons. One button will copy from this input to the user's clipboard. Then we can read from the clipboard to paste into this input.
To do this we can bind an event listener to our Copy button for the event click. For our function we invoke navigator.clipboard.writeText and then the value of our input. If we press our Copy button and then paste into this input, we can see that it's copied the value from the input and pasted into this one.
If we update the value and press Copy again, we can paste again to see the new value. The clipboard API methods return a Promise, so we could await the writeText and then tell our users that we've copied the value. Try that again, we see this alert with "Copied!"
To read from the user's clipboard let's add an event listener to the Paste button. Again, this will be an asynchronous function. Let's declare a variable READ. Its value is await navigator.clipboard.readText. Let's set our input value to that value.
If we check our demo, let's update the value here, press Copy. The value is copied. Then if we press Paste, the value is pasted into our paste input.
In review, we can use the navigator.clipboard API to read and write to a user's clipboard, where each method available returns a promise.