mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-22 15:57:14 +00:00
44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
/**
|
|
* Copies text to clipboard across both HTTP (non-secure context) and HTTPS (secure context).
|
|
*/
|
|
export async function copyToClipboard(text: string): Promise<boolean> {
|
|
if (
|
|
typeof navigator !== 'undefined' &&
|
|
navigator.clipboard &&
|
|
typeof navigator.clipboard.writeText === 'function'
|
|
) {
|
|
try {
|
|
await navigator.clipboard.writeText(text)
|
|
return true
|
|
} catch {
|
|
// Fallback if navigator.clipboard fails or permission is denied
|
|
}
|
|
}
|
|
|
|
// Fallback for non-secure HTTP context using execCommand
|
|
try {
|
|
const textArea = document.createElement('textarea')
|
|
textArea.value = text
|
|
textArea.style.position = 'fixed'
|
|
textArea.style.top = '0'
|
|
textArea.style.left = '0'
|
|
textArea.style.width = '2em'
|
|
textArea.style.height = '2em'
|
|
textArea.style.padding = '0'
|
|
textArea.style.border = 'none'
|
|
textArea.style.outline = 'none'
|
|
textArea.style.boxShadow = 'none'
|
|
textArea.style.background = 'transparent'
|
|
textArea.style.opacity = '0'
|
|
document.body.appendChild(textArea)
|
|
textArea.focus()
|
|
textArea.select()
|
|
const successful = document.execCommand('copy')
|
|
document.body.removeChild(textArea)
|
|
return successful
|
|
} catch (err) {
|
|
console.error('Failed to copy text to clipboard:', err)
|
|
return false
|
|
}
|
|
}
|