copy-to-clipboard icon indicating copy to clipboard operation
copy-to-clipboard copied to clipboard

Copied text/html content not getting pasted in code editor, slack, etc.

Open jasminMerchant opened this issue 3 years ago • 4 comments

This is a great library, but we are facing some issue.

We have used this library in a project to copy an HTML table when clicked on a button. It seems to copy the table content, but while pasting, it is not pasting anything in Code Editor (VS Code in my case), Slack, Skype, and such areas. But when pasted in Notes, Docs, or Pages software, it is pasting the content properly in tabular format.

Has this issue happened before or is there any fix for this?

Any help will be very appreciated!

jasminMerchant avatar Apr 21 '21 19:04 jasminMerchant

I faced the same issue and solve it using that code snippet

const copyToClipboard = (value) => {
  const input = document.createElement('textarea');

  document.body.appendChild(input);
  input.value = value;
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
};

execCommand browsers support is good enough to make that reliable

Hope it helps!

imdmitrykravchenko avatar Aug 11 '21 19:08 imdmitrykravchenko

@jasminMerchant can you provide jsbin or similar sandbox example to reproduce? Maybe, you needed to pass text/html as options.format?

sudodoki avatar Aug 02 '22 22:08 sudodoki

Here's an alternative version that allows you to paste either the rich text, or the plain text, depending on the text box it's being pasted into:

async function copyText (value) {
    const typeRich = 'text/html';
    const blobRich = new Blob([value], { type: typeRich });

    const typePlain = 'text/plain';
    // optionally, replace/remove html tags with plain text equivalents (e.g., newlines instead of <br>)
    // const plainText = replaceHtmlTags(value);
    const blobPlain = new Blob([value], { type: typePlain });

    // Copy both types so it can be pasted into either a Rich Text editor with formatting,
    // or a plain text editor with basic formatting (e.g., new lines but not HTML tags)
    const data = [new ClipboardItem({ [typeRich]: blobRich, [typePlain]: blobPlain })];

    await navigator.clipboard.write(data);
}

klamping avatar Jan 26 '23 20:01 klamping

@klamping Your code works wonderfully. The text copy function in Apple Newsroom works differently. When pasting into the visual studio code(Untitled-1), your code is attached in "html" and the Apple Newsroom code is attached in "plain". What would be different from your code? I think you're right, but I'm curious.

tuffkidd avatar Feb 01 '23 12:02 tuffkidd