Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Failed to construct 'ClipboardItem': Failed to convert value to 'Blob'

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?

like image 245
kaljak Avatar asked Aug 24 '20 13:08

kaljak


Video Answer


1 Answers

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

like image 135
arslan2012 Avatar answered Oct 11 '22 16:10

arslan2012