JavaScript implements copying content to the clipboard

Method 1. The method of copying content to the clipboard varies from browser to browser. Here's a working solution that uses the Clipboard API and provides some browser compatibility handling:

The code here will create a temporary textarea element containing the specified link and add it to the body of the current document. It then selects and copies the text within that element, using  document.execCommand("copy") the command to copy it to the clipboard. Finally, the code will delete the temporary element.

Note that this method requires the user to allow access to the clipboard in the browser. Certain browsers may block this method of access, so it cannot be relied upon.

// 获取要复制到剪切板的链接
const link = "https://www.example.com";

// 创建临时 <textarea> 元素,将链接写入其中
const textArea = document.createElement("textarea");
textArea.value = link;
document.body.appendChild(textArea);

// 选中并复制链接
textArea.select();
document.execCommand("copy");

// 将 <textarea> 元素删除
document.body.removeChild(textArea);

Method 2: The method of copying content to the clipboard varies with browsers. Here's a working solution that uses the Clipboard API and provides some browser compatibility handling:

Here, we first check whether the browser supports the Clipboard API. If the API is not supported by the current browser, the traditional  document.execCommand("copy") method is used to copy the text. For those browsers that support the Clipboard API, we will  navigator.clipboard.writeText(text) copy the text to the clipboard by calling the method. This method is more cumbersome, but it can provide compatibility guarantees in most browsers.

function copyToClipboard(text) {
  // 检查浏览器是否支持 Clipboard API
  if (!navigator.clipboard) {
    // 如果不支持,则使用传统的 document.execCommand("copy") 方式
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    document.execCommand("copy");
    document.body.removeChild(textArea);
    return;
  }

  // 使用 Clipboard API 复制内容到剪切板
  navigator.clipboard.writeText(text).then(
    function() {
      console.log("复制成功");
    },
    function() {
      console.log("复制失败");
    }
  );
}

// 调用 copyToClipboard 函数,传入要复制的文本作为参数
copyToClipboard("这是一段需要复制到剪贴板的文本");

Guess you like

Origin blog.csdn.net/weixin_42415158/article/details/130428020
Recommended