如何解决TypeError:无法构造“ ClipboardItem”:无法将值转换为“ Blob”
我想将文本和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"),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"),title: "" });
});
}
});
但是剪贴板API和事件仍在起作用,我建议使用clipboard.js
之类的替代方法版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。