I want to write text and html to the user clipboard. I am using the code snippet from MDN: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/write
navigator.permissions.query({ name: 'clipboard-write' }).then(result => {
if (result.state === 'granted') {
let data = [new ClipboardItem({ "text/plain": message })];
navigator.clipboard.write(data).then(function() {
$.growl.notice({ message: ResourceService.getKey("CopyToClipboardSuccess"), location: "tc", title: "" });
}, function() {
$.growl.error({ message: ResourceService.getKey("CopyToClipboardError"), location: "tc", title: "" });
});
}
});
All I get is this error:
Uncaught (in promise) TypeError: Failed to construct 'ClipboardItem': Failed to convert value to 'Blob'.
Is there another way to copy text and HTML to the clipboard. What do I miss?
assuming your message is string type, here is a demo code
your code would be
navigator.permissions.query({ name: 'clipboard-write' }).then(result => {
if (result.state === 'granted') {
const type = 'text/plain';
const blob = new Blob([message], { type });
let data = [new ClipboardItem({ [type]: blob })];
navigator.clipboard.write(data).then(function() {
$.growl.notice({ message: ResourceService.getKey("CopyToClipboardSuccess"), location: "tc", title: "" });
}, function() {
$.growl.error({ message: ResourceService.getKey("CopyToClipboardError"), location: "tc", title: "" });
});
}
});
but Clipboard API and events are still working draft, I recommend using an alternatives like clipboard.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With