复制剪切板功能

730 阅读1分钟

分享一个前端复制剪贴板的util方法,相比较30seconds上提供的功能,这个util还采用了navigator.clipboard的API;

首先看一下navigator.clipboard的兼容性:

navigator.clipboard的功能可以覆盖到89.13%;在navigator.clipboard不能生效的时候,就可以采用document.execCommand

在来看一下document.execCommand的兼容性: 可以覆盖达到95.41%的用户,相比较而言document.execCommand对于低版本和IE的兼容性会更好。

下你那就是功能的实现了:

let __textArea;

function getTextArea() {
  if (!__textArea) {
    __textArea = document.createElement('textarea');
    __textArea.style.position = 'fixed';
    __textArea.style.left = '100vw';
    __textArea.style.top = 0;
  }
  return __textArea;
}

export default class ClipboardUtils {

  static async copyTextToClipboard(text) {
    if (navigator.clipboard) {
      return navigator.clipboard.writeText(text);
    }

    // Fallback
    const textArea = getTextArea();
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    const success = document.execCommand('copy');

    document.body.removeChild(textArea);

    if (!success) {
      throw new Error('复制至剪贴簿失败');
    }
    return success;
  }
}