当用户从下拉菜单中 Select 一个选项时,我正在try 将文本写入剪贴板.以下功能适用于除Safari之外的所有浏览器:
<select onChange="writeTextToClipboard(this.value);">
<option value="Text I want to copy">Copy to clipboard</option>
</select>
function writeTextToClipboard(value) {
navigator.clipboard.writeText(value);
}
我知道Safari希望将promise 传递给剪贴板对象的write
函数,因此在this blog post之后,我修改了我的代码:
async function writeTextToClipboard(value) {
// Safari, Chrome
if(typeof ClipboardItem && navigator.clipboard.write) {
const type = 'text/plain'
const blob = new Blob([value], {type})
const cbi = new ClipboardItem({[type]: blob})
await navigator.clipboard.write([cbi])
console.log(`Copied: ${value}`)
}
// Firefox
else {
navigator.clipboard.writeText(value);
}
}
这仍然抛出了NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
Safari上,也打破了Chrome与我错过了什么?NotAllowedError: Invalid Blob types.
我在Safari 17.0上
UPDATES:
- 我修复了Chrome上的这个问题,但仍然不能在Safari上运行.我创造了一个fiddle with a minimal example.
- 我还意识到,当我的示例在按钮的
onClick
处理程序中调用,而不是在 Select 元素的onChange
处理程序中调用时,它可以正常工作.我澄清了我的用例. - 目前我能想到的唯一解决方案是使用
select
元素以外的其他元素重新构建下拉菜单,并对其使用onClick
事件处理程序,但如果可能的话,我想避免这种情况. - 这是asked before,但那篇文章中提到的解决方案使用的是
execCommand()
,这是不建议使用的,也不起作用.