I am working on a Blazor project where I need to copy HTML content to the clipboard. The copy functionality works fine in most browsers (like Chrome, Edge, and Firefox) but fails in Safari, especially on iOS devices. I am using the Clipboard API with a fallback method for cases where the primary API fails.
Here is the code I'm using to copy both HTML and plain text content to the clipboard:
private copyHandler(value: string): void { const tempElement: HTMLElement = document.createElement('div'); tempElement.innerHTML = value; tempElement.style.position = 'fixed'; tempElement.style.opacity = '0'; document.body.appendChild(tempElement); if (navigator.clipboard && navigator.clipboard.write) { navigator.clipboard.write([ new ClipboardItem({'text/html': new Blob([tempElement.innerHTML], { type: 'text/html' }),'text/plain': new Blob([tempElement.innerText], { type: 'text/plain' }) }) ]).then(() => { document.body.removeChild(tempElement); }).catch(() => { this.fallbackCopy(tempElement); document.body.removeChild(tempElement); }); }}private fallbackCopy(element: HTMLElement): void { const selection = window.getSelection(); const range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); try { document.execCommand('copy'); } catch (e) { console.error('Fallback: Copy command failed', e); } selection.removeAllRanges();}In Safari, this code results in the error:Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
I have tried the following approaches to resolve the issue:
Used Fallback Method: Added a fallback method using document.execCommand('copy') in case the Clipboard API fails.Checked Permissions: Verified that Safari has the necessary permissions for clipboard access. However, there are no prompts or indications that the user denied permission.Moved Cleanup Logic: Adjusted the code to ensure that document.body.removeChild() is called only after both the Clipboard API and fallback methods have completed. This change prevents removing the temporary element too early.
My expectation was that the fallback method would at least allow copying in Safari if the primary API failed, but it seems that Safari is blocking the clipboard operation entirely.