Copy Canvas content to clipboard in Javascript in iOS

86 views Asked by At

Trying to copy a Canvas content to the Clipboard within a button click event handler

canvas.toBlob(
blob => { navigator.clipboard.write([new ClipboardItem({'image/png': blob})]) }
)

works well on Chrome Desktop but on iOs (tested on iPad) it results in

notallowederror: the request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

I found out that the issue was related to the fact that clipboard handling must occur within a user-input generated event.

While the above code was within an event handler, the canvas.toBlob call is asynchrounous, resulting in the error.

The fix has been to prepare the blob when the canvas changed, setting the canvasBlob variable and changing the code for the event handler to use the pre-calculated value:

navigator.clipboard.write([new ClipboardItem({'image/png': canvasBlob})])

while this works for applications with a fairly low refresh frequency, it might be problematic when the Canvas is updated frequently, and in any case it implies a potentially large memory allocation, compared to on-the-fly generation.

0

There are 0 answers