clipboard.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import Clipboard from 'clipboard'
  2. import { decrypt } from '@/utils/crypto'
  3. /**
  4. * 复制文本到剪贴板
  5. * @param text 文本内容
  6. */
  7. export const copyText = (text: string) => {
  8. return new Promise((resolve, reject) => {
  9. const fakeElement = document.createElement('button')
  10. const clipboard = new Clipboard(fakeElement, {
  11. text: () => text,
  12. action: () => 'copy',
  13. container: document.body,
  14. })
  15. clipboard.on('success', e => {
  16. clipboard.destroy()
  17. resolve(e)
  18. })
  19. clipboard.on('error', e => {
  20. clipboard.destroy()
  21. reject(e)
  22. })
  23. document.body.appendChild(fakeElement)
  24. fakeElement.click()
  25. document.body.removeChild(fakeElement)
  26. })
  27. }
  28. // 读取剪贴板
  29. export const readClipboard = (): Promise<string> => {
  30. return new Promise((resolve, reject) => {
  31. if (navigator.clipboard?.readText) {
  32. navigator.clipboard.readText().then(text => {
  33. if (!text) reject('剪贴板为空或者不包含文本')
  34. return resolve(text)
  35. })
  36. }
  37. else reject('浏览器不支持或禁止访问剪贴板,请使用快捷键 Ctrl + V')
  38. })
  39. }
  40. // 解析加密后的剪贴板内容
  41. export const pasteCustomClipboardString = (text: string) => {
  42. let clipboardData
  43. try {
  44. clipboardData = JSON.parse(decrypt(text))
  45. }
  46. catch {
  47. clipboardData = text
  48. }
  49. return clipboardData
  50. }
  51. // 尝试解析剪贴板内容是否为Excel表格(或类似的)数据格式
  52. export const pasteExcelClipboardString = (text: string): string[][] | null => {
  53. const lines: string[] = text.split('\r\n')
  54. if (lines[lines.length - 1] === '') lines.pop()
  55. let colCount = -1
  56. const data: string[][] = []
  57. for (const index in lines) {
  58. data[index] = lines[index].split('\t')
  59. if (data[index].length === 1) return null
  60. if (colCount === -1) colCount = data[index].length
  61. else if (colCount !== data[index].length) return null
  62. }
  63. return data
  64. }