Unable to copy text using JavaScript function execCommand('copy')

401 Views Asked by At

I am trying to copy a string value to clipboard using execCommand('copy') in a function which is being called when clicked on copy button. Below is the function:

var s = 'some text';

function clipboard(str) {
  console.log(str);
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};

The above code is only working when I open the page which contains the copy button in the same tab. If I open the page as pop-up window, and click on the copy button, I can see the console log printing the value of the arguments. But that argument value is not copied to clipboard.

I tried the following code & was able to copy the value to clipboard. But with the code below I had to click on the main window for the function to copy the value to clipboard.

var s = 'some text';

function clipboard(str) {
  console.log(str);
  if (!document.hasFocus()) 
  {
    document.addEventListener('click', function() {
      const el = document.createElement('textarea');
      el.value = str;
      el.setAttribute('readonly', '');
      el.style.position = 'absolute';
      el.style.left = '-9999px';
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
    });
  }
};

Please suggest how to make the clipboard function work in pop-up window without clicking back on main body. Thanks.

1

There are 1 best solutions below

0
Marty On

The: document.execCommand('copy'); method is no longer supported and may not function correctly in all situations or browsers. Use the more up-to-date and dependable Clipboard API in its place.

Your clipboard function, which makes use of the Clipboard API, has been updated as follows:

var s = 'some text';

async function clipboard(string) {
  console.log(string);
  try {
    await navigator.clipboard.writeText(string);
    console.log('Text copied!');
  } catch (err) {
    console.error('Failed to copy', err);
  }
}

This function uses the navigator.clipboard and is an async function.To copy the specified text to the clipboard, use the writeText() method. You must use the await keyword to wait for the promise to resolve because the method returns a promise.

This improved feature ought to perform consistently in all circumstances, including pop-up windows.

Be aware that some outdated browsers may not support the Clipboard API. Use a library with fallback methods, such as clipboard.js or clipboard-polyfill, to ensure compatibility.

With both older and newer browsers, compatibility should be guaranteed by this code:

function copyToClipboard(text) {
  // Clipboard API supported
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text)
      .then(() => {
        console.log('Text copied to clipboard');
      })
      .catch(err => {
        console.error('Failed to copy text: ', err);
      });
  } else {
    // Clipboard API not supported
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.setAttribute('readonly', '');
    textarea.style.position = 'absolute';
    textarea.style.left = '-9999px';
    document.body.appendChild(textarea);
    textarea.select();

    try {
      const successful = document.execCommand('copy');
      if (successful) {
        console.log('Text copied');
      } else {
        console.error('Failed to copy');
      }
    } catch (err) {
      console.error('Failed to copy', err);
    }

    document.body.removeChild(textarea);
  }
}