Методы JavaScript для копирования строк в буфер обмена

Чтобы скопировать строку в буфер обмена в JavaScript, вы можете использовать различные методы. Вот несколько часто используемых подходов:

Метод 1. Использование API буфера обмена

function copyToClipboard(text) {
  navigator.clipboard.writeText(text)
    .then(() => {
      console.log('Text copied to clipboard');
    })
    .catch((error) => {
      console.error('Error copying text to clipboard:', error);
    });
}
copyToClipboard('Your string to be copied');

Метод 2: выполнение команды копирования скрытого элемента ввода

function copyToClipboard(text) {
  const input = document.createElement('input');
  input.value = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
}
copyToClipboard('Your string to be copied');

Метод 3. Использование элемента textarea

function copyToClipboard(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}
copyToClipboard('Your string to be copied');

Метод 4. Использование методов document.queryCommandSupported и document.execCommand

function copyToClipboard(text) {
  if (document.queryCommandSupported('copy')) {
    const textarea = document.createElement('textarea');
    textarea.textContent = text;
    textarea.style.position = 'fixed';
    document.body.appendChild(textarea);
    textarea.select();
    try {
      document.execCommand('copy');
      console.log('Text copied to clipboard');
    } catch (error) {
      console.error('Error copying text to clipboard:', error);
    } finally {
      document.body.removeChild(textarea);
    }
  }
}
copyToClipboard('Your string to be copied');

Эти методы предоставляют различные способы копирования строки в буфер обмена в JavaScript. Не стесняйтесь выбирать тот, который лучше всего соответствует вашим потребностям.