Skip to content

Instantly share code, notes, and snippets.

@JCloudYu
Created August 21, 2024 06:48
Show Gist options
  • Save JCloudYu/8b3e1066df137f2ec09965634f073903 to your computer and use it in GitHub Desktop.
Save JCloudYu/8b3e1066df137f2ec09965634f073903 to your computer and use it in GitHub Desktop.
const clipboardWrite = (()=>{
const callHandlers = [];
window.addEventListener('copy', (e)=>{
if (callHandlers.length <= 0) return;
const handler = callHandlers.shift();
return handler(e);
});
return function(data, mime = 'text/plain') {
return new Promise((res, rej) => {
// https://developer.mozilla.org/en-US/docs/Web/API/Clipboard
// This will only available in modern browser and http sites
/*
if (window.navigator && navigator.clipboard) {
const blob = new Blob([data], {type: mime});
return navigator.clipboard.write([new ClipboardItem({[mime]: blob})]).then(res).catch(rej);
}
*/
// Old fashioned style
callHandlers.push((evt)=>{
evt.preventDefault();
evt.clipboardData.setData(mime, data);
setTimeout(res, 0);
});
setTimeout(()=>document.execCommand('copy'), 0);
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment