/html-dom /Intermediate
GitHub 5008★

Copy text to the clipboard

Assume that we want to copy a given text, text, to the clipboard.

In order to do that, we create a fake textarea element with value as text. Next, we select the content and execute the "Copy" command.

// Create a fake textarea
const textAreaEle = document.createElement('textarea');

// Reset styles
textAreaEle.style.border = '0';
textAreaEle.style.padding = '0';
textAreaEle.style.margin = '0';

// Set the absolute position
// User won't see the element
textAreaEle.style.position = 'absolute';
textAreaEle.style.left = '-9999px';
textAreaEle.style.top = `${document.documentElement.scrollTop}px`;

// Set the value
textAreaEle.value = text;

// Append the textarea to body

// Focus and select the text

// Execute the "copy" command
try {
} catch (err) {
// Unable to copy
} finally {
// Remove the textarea

See also

Follow me on and to get more useful contents.