node.js copy to clipboard code example
Example 1: javascript copy to clipboard
function copyToClipboard(text) {
var input = document.body.appendChild(document.createElement("input"));
input.value = text;
input.focus();
input.select();
document.execCommand('copy');
input.parentNode.removeChild(input);
}
Example 2: js copy string to clipboard
const el = document.createElement('textarea');
el.value = str; //str is your string to copy
document.body.appendChild(el);
el.select();
document.execCommand('copy'); // Copy command
document.body.removeChild(el);
Example 3: javascript copy to clipboard
const copyToClipboard = () => {
navigator.permissions.query({name: "clipboard-write"}).then(result => {
if (result.state == "granted" || result.state == "prompt") {
// write to the clipboard now
updateClipboard('I copy this string');
}
});
};
const updateClipboard = (newClip) => {
navigator.clipboard.writeText(newClip).then(() => {
// clipboard successfully set
console.log('success');
}, () => {
// clipboard write failed
console.log('Failed to copy');
});
};
const btn = document.getElementById('copy-button');
btn.addEventListener('click', copyHashtagToClipboard);
Example 4: node.js copy to clipboard
// Copy to clipboard in node.js
const child_process = require('child_process')
// This uses an external application for clipboard access, so fill it in here
// Some options: pbcopy (macOS), xclip (Linux or anywhere with Xlib)
const COPY_APP = 'xclip'
function copy(data, encoding='utf8') {
const proc = child_process.spawn(COPY_APP)
proc.stdin.write(data, {encoding})
proc.stdin.end()
}