diff --git a/src/components/itemContextMenu.js b/src/components/itemContextMenu.js index b42584d016..56fd3705db 100644 --- a/src/components/itemContextMenu.js +++ b/src/components/itemContextMenu.js @@ -1,4 +1,5 @@ import browser from '../scripts/browser'; +import { copy } from '../scripts/clipboard'; import globalize from '../scripts/globalize'; import actionsheet from './actionSheet/actionSheet'; import { appHost } from './apphost'; @@ -366,32 +367,11 @@ import toast from './toast/toast'; break; case 'copy-stream': { const downloadHref = apiClient.getItemDownloadUrl(itemId); - const textAreaCopy = function () { - const textArea = document.createElement('textarea'); - textArea.value = downloadHref; - document.body.appendChild(textArea); - textArea.focus(); - textArea.select(); - - if (document.execCommand('copy')) { - toast(globalize.translate('CopyStreamURLSuccess')); - } else { - prompt(globalize.translate('CopyStreamURL'), downloadHref); - } - document.body.removeChild(textArea); - }; - - /* eslint-disable-next-line compat/compat */ - if (navigator.clipboard === undefined) { - textAreaCopy(); - } else { - /* eslint-disable-next-line compat/compat */ - navigator.clipboard.writeText(downloadHref).then(function () { - toast(globalize.translate('CopyStreamURLSuccess')); - }).catch(function () { - textAreaCopy(); - }); - } + copy(downloadHref).then(() => { + toast(globalize.translate('CopyStreamURLSuccess')); + }).catch(() => { + prompt(globalize.translate('CopyStreamURL'), downloadHref); + }); getResolveFunction(resolve, id)(); break; } diff --git a/src/scripts/clipboard.js b/src/scripts/clipboard.js new file mode 100644 index 0000000000..efa465823a --- /dev/null +++ b/src/scripts/clipboard.js @@ -0,0 +1,45 @@ +/** + * Copies text to the clipboard using the textarea. + * @param {string} text - Text to copy. + * @returns {Promise} Promise. + */ +function textAreaCopy(text) { + const textArea = document.createElement('textarea'); + textArea.value = text; + document.body.appendChild(textArea); + textArea.focus(); + textArea.select(); + + let ret; + + try { + if (document.execCommand('copy')) { + ret = Promise.resolve(); + } else { + ret = Promise.reject(); + } + } catch (_) { + ret = Promise.reject(); + } + + document.body.removeChild(textArea); + + return ret; +} + +/** + * Copies text to the clipboard. + * @param {string} text - Text to copy. + * @returns {Promise} Promise. + */ +export function copy(text) { + /* eslint-disable-next-line compat/compat */ + if (navigator.clipboard === undefined) { + return textAreaCopy(text); + } else { + /* eslint-disable-next-line compat/compat */ + return navigator.clipboard.writeText(text).catch(() => { + return textAreaCopy(text); + }); + } +}