Cách sao chép văn bản

Joe Medley
Joe Medley

Cắt và dán văn bản là một trong những tính năng được dùng phổ biến nhất của các ứng dụng nói chung và ứng dụng dành cho máy tính nói riêng. Làm cách nào để sao chép văn bản trên web? Có một cách cũ và một cách mới. Điều này còn tuỳ thuộc vào trình duyệt được sử dụng.

Cách làm hiện đại

Sử dụng Async Clipboard API

Phương thức Clipboard.writeText() nhận một chuỗi và trả về một Promise (lời hứa) sẽ phân giải khi văn bản được ghi thành công vào bảng nhớ tạm. Clipboard.writeText() chỉ có thể được dùng từ đối tượng window có tiêu điểm.

Browser Support

  • Chrome: 66.
  • Edge: 79.
  • Firefox: 63.
  • Safari: 13.1.

Source

Cách cổ điển

Sử dụng document.execCommand()

Khi gọi document.execCommand('copy'), hệ thống sẽ trả về một giá trị boolean cho biết liệu thao tác sao chép có thành công hay không. Gọi lệnh này trong một cử chỉ của người dùng, chẳng hạn như trình xử lý sự kiện nhấp. Cách này có những hạn chế so với Async Clipboard API. Phương thức execCommand() chỉ hoạt động với các phần tử DOM. Vì đây là hoạt động đồng bộ, nên việc sao chép một lượng lớn dữ liệu (đặc biệt là dữ liệu phải được chuyển đổi hoặc làm sạch theo cách nào đó) có thể chặn trang.

Browser Support

  • Chrome: 1.
  • Edge: 12.
  • Firefox: 69.
  • Safari: 1.3.

Source

Cải tiến tăng dần

const copyButton = document.querySelector('#copyButton');
const out = document.querySelector('#out');

if ('clipboard' in navigator) {
  copyButton.addEventListener('click', () => {
    navigator.clipboard.writeText(out.value)
    .then(() => {
      console.log('Text copied');
    })
    .catch((err) => console.error(err.name, err.message));
  });
} else {
  copyButton.addEventListener('click', () => {
    const textArea = document.createElement('textarea');
    textArea.value = out.value;
    textArea.style.opacity = 0;
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
      const success = document.execCommand('copy');
      console.log(`Text copy was ${success ? 'successful' : 'unsuccessful'}.`);
    } catch (err) {
      console.error(err.name, err.message);
    }
    document.body.removeChild(textArea);
  });
}

Tài liệu đọc thêm

Bản minh hoạ

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="icon"
      href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
    />
    <title>How to copy text</title>
  </head>
  <body>
    <h1>How to copy text</h1>
    <textarea rows="3">
Some sample text for you to copy. Feel free to edit this.</textarea
    >
    <button type="button">Copy</button>
  </body>
</html>

CSS


        :root {
  color-scheme: dark light;
}

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 1rem;
  font-family: system-ui, sans-serif;
}

button {
  display: block;
}
        

JS


        const textarea = document.querySelector('textarea');
const button = document.querySelector('button');

button.addEventListener('click', async () => {
  try {
    await navigator.clipboard.writeText(textarea.value);
  } catch (err) {
    console.error(err.name, err.message);
  }
});