Open jasminMerchant opened 3 years ago
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!
@jasminMerchant can you provide jsbin or similar sandbox example to reproduce? Maybe, you needed to pass text/html
as options.format?
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 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.
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!