From 01fc9e74a9244bf69aaaf4d7dd38ecb9fe80f774 Mon Sep 17 00:00:00 2001 From: Dominik Pschenitschni Date: Fri, 9 Sep 2022 14:15:40 +0200 Subject: [PATCH] feat: add fallback for useCopyToClipboard --- src/composables/useCopyToClipboard.ts | 35 +++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/composables/useCopyToClipboard.ts b/src/composables/useCopyToClipboard.ts index 30ea37456..69fa19140 100644 --- a/src/composables/useCopyToClipboard.ts +++ b/src/composables/useCopyToClipboard.ts @@ -3,11 +3,42 @@ import {useI18n} from 'vue-i18n' export function useCopyToClipboard() { const {t} = useI18n({useScope: 'global'}) - + + function fallbackCopyTextToClipboard(text: string) { + const textArea = document.createElement('textarea') + textArea.value = text + + // Avoid scrolling to bottom + textArea.style.top = '0' + textArea.style.left = '0' + textArea.style.position = 'fixed' + + document.body.appendChild(textArea) + textArea.focus() + textArea.select() + + try { + // NOTE: the execCommand is deprecated but as of 2022_09 + // widely supported and works without https + const successful = document.execCommand('copy') + if (!successful) { + throw new Error() + } + } catch (err) { + error(t('misc.copyError')) + } + + document.body.removeChild(textArea) + } + return async (text: string) => { + if (!navigator.clipboard) { + fallbackCopyTextToClipboard(text) + return + } try { await navigator.clipboard.writeText(text) - } catch { + } catch(e) { error(t('misc.copyError')) } } -- 2.40.1