copy text utility

Requirement: copy platform link text

accomplish:

//复制文字
function copyText(text: string) {
  var input = document.createElement("input");
  input.value = text;
  document.body.appendChild(input);
  input.select();
  navigator.clipboard.writeText(text);
  document.body.removeChild(input); // 删除临时实例
  console.log('链接复制成功!');//修改自己需要的提示
}

question:

The Clipboard interface implements the Clipboard API, which provides read and write access to the system clipboard if the user grants the corresponding permissions. In web applications, the Clipboard API can be used to implement cut, copy, and paste functionality. The system clipboard is exposed in the global property Navigator.clipboard. If the user has not granted the appropriate permission and the "clipboard-read"​ or "clipboard-write"​ permission using the Permissions API in due course, calling methods on the Clipboard object will not succeed. An error will be reported on the deployment line.

So the change is as follows: But (document.execCommand is about to be discarded) it is better to use the copy plug-in later.

// 先给要复制的文本或者按钮加上点击事件后,并将要复制的值传过来
async function copyText(val: string) {
  if (navigator.clipboard && window.isSecureContext) {
    hlAlert('链接复制成功!', 1);
    return navigator.clipboard.writeText(val);
  } else {
    const textArea = document.createElement('textarea');
    textArea.value = val;
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    hlAlert('链接复制成功!', 1);
    return new Promise((res: any, rej: any) => {
      document.execCommand('copy') ? res() : rej();
      textArea.remove();
    })
  }
}

Guess you like

Origin blog.csdn.net/enhenglhm/article/details/128949917