问题描述
我想将文本和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
之类的替代方法