From 43bfa3ca51a90f21bac4ebd5616cada96d74212d Mon Sep 17 00:00:00 2001 From: FoxxMD Date: Mon, 31 Oct 2022 11:30:17 -0400 Subject: [PATCH] fix(ui): Add workaround for removal reason copy-to-clipboard when in unsecure context --- src/Web/assets/views/config.ejs | 36 +++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/src/Web/assets/views/config.ejs b/src/Web/assets/views/config.ejs index 2ed61c46..7a38fc50 100644 --- a/src/Web/assets/views/config.ejs +++ b/src/Web/assets/views/config.ejs @@ -151,7 +151,7 @@ problems.append(wrapper); } - window.canSave = <%= canSave %>; + window.canSave = <%= canSave ?? false %>; window.isGuest = false; if (searchParams.get('subreddit') === null) { @@ -342,6 +342,35 @@ return new Promise((resolve, reject) => resolve(url)); } + // https://stackoverflow.com/a/65996386 + // if the user is accessing CM from an unsecure context + // -- http and NOT http://localhost + // then navigator.clipboard is not available and we need to fallback to execCommand + function copyToClipboard(textToCopy) { + // navigator clipboard api needs a secure context (https) + if (navigator.clipboard && window.isSecureContext) { + // navigator clipboard api method + return navigator.clipboard.writeText(textToCopy); + } else { + debugger; + // text area method + let textArea = document.createElement("textarea"); + textArea.value = textToCopy; + // make the textarea out of viewport + textArea.style.position = "fixed"; + textArea.style.left = "-999999px"; + textArea.style.top = "-999999px"; + document.body.appendChild(textArea); + textArea.focus(); + textArea.select(); + return new Promise((res, rej) => { + // here the magic happens + document.execCommand('copy') ? res() : rej(); + textArea.remove(); + }); + } + } + window.addEventListener('load', function () { var searchParams = new URLSearchParams(window.location.search); @@ -442,7 +471,10 @@ copy.insertAdjacentHTML('beforeend', `Copy ID `); copy.addEventListener('click', e => { e.preventDefault(); - navigator.clipboard.writeText(reason.id); + copyToClipboard(reason.id) + .catch((e) => { + console.log(`Could not copy ID ${reason.id} to clipboard due to an error`, e); + }); }); node.appendChild(copy); reasonsList.appendChild(node);