kal*_*jak 6 javascript clipboard google-chrome
我想将文本和 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: "" });
});
}
});
Run Code Online (Sandbox Code Playgroud)
我得到的只是这个错误:
Uncaught (in promise) TypeError: Failed to construct 'ClipboardItem': Failed to convert value to 'Blob'.
Run Code Online (Sandbox Code Playgroud)
还有另一种方法可以将文本和 HTML 复制到剪贴板。我想念什么?
假设您的消息是字符串类型,这里是一个演示代码
你的代码是
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: "" });
});
}
});
Run Code Online (Sandbox Code Playgroud)
但剪贴板 API 和事件仍在草案中,我建议使用像clipboard.js这样的替代品
| 归档时间: |
|
| 查看次数: |
1540 次 |
| 最近记录: |