[HTML 5] Async clioboard
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
const app = document.getElementById('app');
app.innerHTML = `
<h1>JavaScript HTML5 APIs</h1>
<pre class="source" contenteditable>export class Pizza extends Food {
constructor (private name: string) {}
}</pre>
<button type="button" class="copy">Copy</button>
<button type="button" class="paste">Paste</button>
<div class="destination"></div>
<style>
.source {
background: #15181e;
text-align: left;
max-width: 95%;
margin: 25px auto;
font-size: 16px;
color: #fff;
padding: 25px;
border-radius: 5px;
box-sizing: border-box;
}
</style>
`;
const init = () => {
const source = document.querySelector('.source');
const destination = document.querySelector('.destination');
const copy = document.querySelector('.copy');
const paste = document.querySelector('.paste');
const copyToClipboard = async () => {
try {
await navigator.clipboard.writeText(source.innerText);
console.log('Copied!');
} catch (e) {
console.log('Failed to copy!', e);
}
};
const pasteToClipboard = async () => {
try {
const text = await navigator.clipboard.readText();
console.log(`Paste... ${text}`);
destination.innerText = text;
} catch (e) {
console.log('Failed to paste!', e);
}
};
copy.addEventListener('click', copyToClipboard);
paste.addEventListener('click', pasteToClipboard);
document.addEventListener('copy', (e) => {
e.preventDefault();
e.clipboardData.setData(
'text/plain',
e.target.innerText.replace('Pizza', 'Burger')
);
});
document.addEventListener('paste', (e) => {
e.preventDefault();
const text = e.clipboardData.getData('text/plain');
destination.innerText = text;
});
};
if ('clipboard' in window.navigator) {
init();
}