Skip to content

Commit

Permalink
utils: Add function to facilitate copying texts
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaellehmkuhl committed Jan 28, 2025
1 parent d7ec01f commit 76b18a5
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/libs/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,27 @@ export const isElectron = (): boolean => {

return false
}

/**
* Copy text to clipboard
* @param {string} text The text to copy
* @returns {Promise<void>} A promise that resolves when the text is copied
*/
export const copyToClipboard = async (text: string): Promise<void> => {
try {
if (navigator && navigator.clipboard) {
await navigator.clipboard.writeText(text)
} else {
const textArea = document.createElement('textarea')
textArea.value = text
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
document.execCommand('copy')
document.body.removeChild(textArea)
window.scrollTo(0, 0)
}
} catch (error) {
throw new Error(`Failed to copy text. Error: ${error}`)
}
}

0 comments on commit 76b18a5

Please sign in to comment.