js 复制三种方式

93 阅读1分钟

第一种

let copyObj = document.createElement("input");
document.body.appendChild(copyObj);
copyObj.value = this.successLink;
copyObj.select();
document.execCommand("copy");
copyObj.remove();

第二种

import { ElMessage } from 'element-plus'

const useCopy = (content, type='text') => {
  let copyObj;
  if(type === 'text'){
    copyObj = document.createElement('div')
    document.body.appendChild(copyObj)
    copyObj.innerHTML = content
  }else{
    copyObj = document.getElementById(content)
  }
  if(window.getSelection){
    let selection = window.getSelection()
    selection.removeAllRanges()
    let range = document.createRange()
    range.selectNodeContents(copyObj)
    selection.addRange(range)
  }else{
    let range = document.body.createTextRange()
    range.moveToElementText(copyObj)
    range.select()
  }
  document.execCommand('copy')
  window.getSelection().removeAllRanges()
  if(type === 'text'){
    copyObj.remove()
  }
  ElMessage({
    message: '复制成功',
    grouping: true,
    type: 'success',
  })
}

export default useCopy

第三种(异步复制数据,仅在localhost和https下生效)

  if (/webOS|iPhone|iPod/i.test(navigator.userAgent)) {
    try {
      await navigator.clipboard.write([
        new ClipboardItem({
          "text/plain": new Promise(async (resolve) => {
            let text = await axios(xxx);
            resolve(new Blob([text], { type: "text/plain" }));
          }),
        }),
      ]);
      ElMessage.success("复制成功");
    } catch (e) {
      ElMessage.error(e);
    }
    return;
  }