how to get content from clipboard in javascript code example
Example 1: javascript text to clipboard
function copyToClipboard(text) {
const elem = document.createElement('textarea');
elem.value = text;
document.body.appendChild(elem);
elem.select();
document.execCommand('copy');
document.body.removeChild(elem);
}
Example 2: javascript copy to clipboard
const copyToClipboard = () => {
navigator.permissions.query({name: "clipboard-write"}).then(result => {
if (result.state == "granted" || result.state == "prompt") {
updateClipboard('I copy this string');
}
});
};
const updateClipboard = (newClip) => {
navigator.clipboard.writeText(newClip).then(() => {
console.log('success');
}, () => {
console.log('Failed to copy');
});
};
const btn = document.getElementById('copy-button');
btn.addEventListener('click', copyHashtagToClipboard);