diff options
author | Netduma Luke M <luke.meppem@netduma.com> | 2021-10-19 11:22:16 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-10-19 18:22:16 +0800 |
commit | 9f3d5c0a23e5235c613243bc921a880aa6eba6bc (patch) | |
tree | a9fd113afdde82c8c0b132b8d70262f597aa9a29 /web_src/js | |
parent | eaf493be5d01332966f983f6d83ad515cfdec7bf (diff) | |
download | gitea-9f3d5c0a23e5235c613243bc921a880aa6eba6bc.tar.gz gitea-9f3d5c0a23e5235c613243bc921a880aa6eba6bc.zip |
Re-allow clipboard copy on non-https sites (#17118)
* Re-allow clipboard copy on non-https sites
* fallback clipboard functions
Diffstat (limited to 'web_src/js')
-rw-r--r-- | web_src/js/features/clipboard.js | 33 |
1 files changed, 32 insertions, 1 deletions
diff --git a/web_src/js/features/clipboard.js b/web_src/js/features/clipboard.js index 4781f8d6ff..2c7ad013bd 100644 --- a/web_src/js/features/clipboard.js +++ b/web_src/js/features/clipboard.js @@ -16,6 +16,33 @@ function onError(btn) { btn.dataset.content = btn.dataset.original; } +/** + * Fallback to use if navigator.clipboard doesn't exist. + * Achieved via creating a temporary textarea element, selecting the text, and using document.execCommand. + */ +function fallbackCopyToClipboard(text) { + if (!document.execCommand) return false; + + const tempTextArea = document.createElement('textarea'); + tempTextArea.value = text; + + // avoid scrolling + tempTextArea.style.top = 0; + tempTextArea.style.left = 0; + tempTextArea.style.position = 'fixed'; + + document.body.appendChild(tempTextArea); + + tempTextArea.select(); + + // if unsecure (not https), there is no navigator.clipboard, but we can still use document.execCommand to copy to clipboard + const success = document.execCommand('copy'); + + document.body.removeChild(tempTextArea); + + return success; +} + export default function initGlobalCopyToClipboardListener() { document.addEventListener('click', async (e) => { let target = e.target; @@ -33,7 +60,11 @@ export default function initGlobalCopyToClipboardListener() { await navigator.clipboard.writeText(text); onSuccess(target); } catch { - onError(target); + if (fallbackCopyToClipboard(text)) { + onSuccess(target); + } else { + onError(target); + } } break; } |