Update copy to clipboard
This commit is contained in:
@ -2,7 +2,7 @@
|
||||
title: copyToClipboard
|
||||
tags: browser,string,event,advanced
|
||||
firstSeen: 2017-12-31T11:40:33+02:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
lastUpdated: 2022-01-11T09:32:04+02:00
|
||||
---
|
||||
|
||||
Copies a string to the clipboard.
|
||||
@ -13,7 +13,7 @@ Only works as a result of user action (i.e. inside a `click` event listener).
|
||||
- Use `Document.execCommand('copy')` to copy to the clipboard.
|
||||
- Remove the `<textarea>` element from the HTML document.
|
||||
- Finally, use `Selection().addRange()` to recover the original selected range (if any).
|
||||
- **Note:** You can use the new asynchronous Clipboard API to implement the same functionality. It's experimental but should be used in the future instead of this snippet. Find out more about it [here](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).
|
||||
- **Note:** You can use the asynchronous [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) in most current browsers. You can find out more about it in the [copyToClipboardAsync snippet](/js/s/copy-to-clipboard-async).
|
||||
|
||||
```js
|
||||
const copyToClipboard = str => {
|
||||
|
||||
25
snippets/copyToClipboardAsync.md
Normal file
25
snippets/copyToClipboardAsync.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: copyToClipboardAsync
|
||||
tags: browser,string,promise,advanced
|
||||
firstSeen: 2022-01-11T05:00:00-04:00
|
||||
---
|
||||
|
||||
Copies a string to the clipboard, returning a promise that resolves when the clipboard's contents have been updated.
|
||||
|
||||
- Check if the [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) is available. Use an `if` statement to ensure `Navigator`, `Navigator.clipboard` and `Navigator.clipboard.writeText` are truthy.
|
||||
- Use `Clipboard.writeText()` to write the given value, `str`, to the clipboard.
|
||||
- Return the result of `Clipboard.writeText()`, which is a promise that resolves when the clipboard's contents have been updated.
|
||||
- In case that the Clipboard API is not available, use `Promise.reject()` to reject with an appropriate message.
|
||||
- **Note:** If you need to support older browsers, you might want to use `Document.execCommand('copy')` instead. You can find out more about it in the [copyToClipboard snippet](/js/s/copy-to-clipboard).
|
||||
|
||||
```js
|
||||
const copyToClipboardAsync = str => {
|
||||
if (navigator && navigator.clipboard && navigator.clipboard.writeText)
|
||||
return navigator.clipboard.writeText(str);
|
||||
return Promise.reject('The Clipboard API is not available.');
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
copyToClipboardAsync('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
|
||||
```
|
||||
Reference in New Issue
Block a user