clipboard.ts 2.0 KB
Newer Older
1 2 3 4 5 6 7 8 9
import {
  API_GET_CLIPBOARD_DATA,
  API_SET_CLIPBOARD_DATA,
  API_TYPE_GET_CLIPBOARD_DATA,
  API_TYPE_SET_CLIPBOARD_DATA,
  SetClipboardDataOptions,
  SetClipboardDataProtocol,
  defineAsyncApi,
} from '@dcloudio/uni-api'
10
// import { showModal } from '../../api/ui/popup/showModal'
11 12
import {
  useI18n,
13
  // initI18nSetClipboardDataMsgsOnce,
14 15 16 17 18 19 20 21 22 23 24 25
  initI18nGetClipboardDataMsgsOnce,
} from '@dcloudio/uni-core'

export const getClipboardData = defineAsyncApi<API_TYPE_GET_CLIPBOARD_DATA>(
  API_GET_CLIPBOARD_DATA,
  async (_, { resolve, reject }) => {
    initI18nGetClipboardDataMsgsOnce()
    const { t } = useI18n()
    try {
      const data = await navigator.clipboard.readText()
      resolve({ data })
    } catch (error: any) {
26 27 28
      _getClipboardData(resolve, () => {
        reject(`${error} ${t('uni.getClipboardData.fail')}`)
      })
29 30 31 32 33 34 35 36 37 38 39
    }
  }
)

export const setClipboardData = defineAsyncApi<API_TYPE_SET_CLIPBOARD_DATA>(
  API_SET_CLIPBOARD_DATA,
  async ({ data }, { resolve, reject }) => {
    try {
      await navigator.clipboard.writeText(data)
      resolve()
    } catch (error) {
40
      _setClipboardData(data, resolve, reject)
41 42 43 44 45
    }
  },
  SetClipboardDataProtocol,
  SetClipboardDataOptions
)
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

function _getClipboardData(resolve: Function, reject: Function) {
  const pasteText = document.getElementById('#clipboard') as HTMLInputElement
  const data = pasteText ? pasteText.value : undefined
  if (data) {
    resolve({ data })
  } else {
    reject()
  }
}

function _setClipboardData(data: string, resolve: Function, reject: Function) {
  const pasteText = document.getElementById('#clipboard')
  pasteText && pasteText.remove()
  const textarea = document.createElement('textarea')
  textarea.id = '#clipboard'
  textarea.style.position = 'fixed'
  textarea.style.top = '-9999px'
  textarea.style.zIndex = '-9999'
  document.body.appendChild(textarea)
  textarea.value = data
  textarea.focus()
  textarea.select()
  const result = document.execCommand('Copy', false)
  textarea.blur()
  if (result) {
    resolve()
  } else {
    reject()
  }
}