Fix copy actions for non-HTTPS/localhost

Fixes #2352
This commit is contained in:
Cohee
2025-01-16 01:55:26 +02:00
parent 0441a8725f
commit 6e2b5d5dc8
2 changed files with 46 additions and 33 deletions

View File

@ -391,6 +391,26 @@ export function getStringHash(str, seed = 0) {
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
}
/**
* Copy text to clipboard. Use navigator.clipboard.writeText if available, otherwise use document.execCommand.
* @param {string} text - The text to copy to the clipboard.
* @returns {Promise<void>} A promise that resolves when the text has been copied to the clipboard.
*/
export function copyText(text) {
if (navigator.clipboard) {
return navigator.clipboard.writeText(text);
}
const parent = document.querySelector('dialog[open]:last-of-type') ?? document.body;
const textArea = document.createElement('textarea');
textArea.value = text;
parent.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
parent.removeChild(textArea);
}
/**
* Map of debounced functions to their timers.
* Weak map is used to avoid memory leaks.