Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clipboard code not working (in Safari) when used in promise #111

Open
jonasdekeukelaere opened this issue Apr 18, 2023 · 0 comments
Open

Comments

@jonasdekeukelaere
Copy link
Member

The security measures kick in when we are trying to use the Clipboard API in an async context: 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.

See https://wolfgangrittner.dev/how-to-use-clipboard-api-in-safari/ and https://wolfgangrittner.dev/how-to-use-clipboard-api-in-firefox/

The last link has a working solution:

if(typeof ClipboardItem && navigator.clipboard.write) {
  // NOTE: Safari locks down the clipboard API to only work when triggered
  //   by a direct user interaction. You can't use it async in a promise.
  //   But! You can wrap the promise in a ClipboardItem, and give that to
  //   the clipboard API.
  //   Found this on https://developer.apple.com/forums/thread/691873
  const text = new ClipboardItem({
	"text/plain": fetch(someUrl)
	  .then(response => response.text())
	  .then(text => new Blob([text], { type: "text/plain" }))
  })
  navigator.clipboard.write([text])
}
else {
  // NOTE: Firefox has support for ClipboardItem and navigator.clipboard.write,
  //   but those are behind `dom.events.asyncClipboard.clipboardItem` preference.
  //   Good news is that other than Safari, Firefox does not care about
  //   Clipboard API being used async in a Promise.
  fetch(someUrl)
	.then(response => response.text())
	.then(text => navigator.clipboard.writeText(text))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant