javascript - 类型错误 : Failed to construct 'ClipboardItem' : Failed to convert value to 'Blob'

标签 javascript google-chrome clipboard

我想将文本和 html 写入用户剪贴板。我正在使用来自 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: "" });
        });
    }
});
我得到的只是这个错误:
Uncaught (in promise) TypeError: Failed to construct 'ClipboardItem': Failed to convert value to 'Blob'.
是否有另一种方法可以将文本和 HTML 复制到剪贴板。我想念什么?

最佳答案

假设您的消息是字符串类型,here is a demo code
你的代码是

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: "" });
        });
    }
});
但剪贴板 API 和事件仍在草稿中,我建议使用 clipboard.js 之类的替代方法

关于javascript - 类型错误 : Failed to construct 'ClipboardItem' : Failed to convert value to 'Blob' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63561767/

相关文章:

javascript - 在 Typescript 中通过 For 循环在 Canvas 上绘制线条不会呈现

javascript - 为什么使用ajax加载时警报功能不起作用

clipboard - 删除剪贴板中文本字符串中的空格

c# - 关闭程序后保留剪贴板信息

javascript - Angular VS 2015 MVC 自定义指令意外标识符和预期;错误

javascript - Jquery 添加计算值

html - webkit滚动条自定义垂直高度

javascript - scrollTo() 和 jquery scrollTop() 在 Chrome 中不起作用

google-chrome - Chrome : Form Border Radius Different than Firefox

javascript - 将 SVG 作为图像复制到剪贴板