Skip to content

Commit 9f3d5c0

Browse files
authoredOct 19, 2021
Re-allow clipboard copy on non-https sites (#17118)
* Re-allow clipboard copy on non-https sites * fallback clipboard functions
1 parent eaf493b commit 9f3d5c0

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed
 

‎web_src/js/features/clipboard.js

+32-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,33 @@ function onError(btn) {
1616
btn.dataset.content = btn.dataset.original;
1717
}
1818

19+
/**
20+
* Fallback to use if navigator.clipboard doesn't exist.
21+
* Achieved via creating a temporary textarea element, selecting the text, and using document.execCommand.
22+
*/
23+
function fallbackCopyToClipboard(text) {
24+
if (!document.execCommand) return false;
25+
26+
const tempTextArea = document.createElement('textarea');
27+
tempTextArea.value = text;
28+
29+
// avoid scrolling
30+
tempTextArea.style.top = 0;
31+
tempTextArea.style.left = 0;
32+
tempTextArea.style.position = 'fixed';
33+
34+
document.body.appendChild(tempTextArea);
35+
36+
tempTextArea.select();
37+
38+
// if unsecure (not https), there is no navigator.clipboard, but we can still use document.execCommand to copy to clipboard
39+
const success = document.execCommand('copy');
40+
41+
document.body.removeChild(tempTextArea);
42+
43+
return success;
44+
}
45+
1946
export default function initGlobalCopyToClipboardListener() {
2047
document.addEventListener('click', async (e) => {
2148
let target = e.target;
@@ -33,7 +60,11 @@ export default function initGlobalCopyToClipboardListener() {
3360
await navigator.clipboard.writeText(text);
3461
onSuccess(target);
3562
} catch {
36-
onError(target);
63+
if (fallbackCopyToClipboard(text)) {
64+
onSuccess(target);
65+
} else {
66+
onError(target);
67+
}
3768
}
3869
break;
3970
}

0 commit comments

Comments
 (0)
Please sign in to comment.