Hey there! I have been facing a similar issue in my job, but I figured out a working solution (I had to dig a LOT to find it).
The main issue is that Apple's Clipboard API expects a Promise when writing something to the clipboard. writeText takes just a string. I wish writeText worked for me since it would make the component logic a lot cleaner, but I managed to get to get this logic working using write
Here is my fix:
const clipboardItem = new ClipboardItem({
'text/plain': someAsyncMethod().then((result) => {
/**
* We have to return an empty string to the clipboard if something bad happens, otherwise the
* return type for the ClipBoardItem is incorrect.
*/
if (!result) {
return new Promise(async (resolve) => {
resolve(new Blob[``]())
})
}
const copyText = `some string`
return new Promise(async (resolve) => {
resolve(new Blob([copyText]))
})
}),
})
// Now, we can write to the clipboard in Safari
navigator.clipboard.write([clipboardItem])
I adapted this code a bit from the actual business logic since it wouldn't make sense without context. But basically, to get get the Clipboard API working, you need to:
Create a new ClipboardItem instance
The ClipboardItem can have "regular" logic in the method body (do whatever you need to here)
IMPORTANT PART: the method body for the new ClipboardItem should return a new Promise that contains resolve(new Blob([<DATA_TO_COPY>])
Topic:
Safari & Web
SubTopic:
General
Tags: