Wuj
Wuj

Reputation: 91

navigator.clipboard.writeText() not working on specific IOS devices

I'm currently using navigator.clipboard.writeText()to copy a value from an element to the clipboard however, its seems to work on all devices apart from the iPhone X and iPhone 6 Plus in safari.

The browsers are up to date and according to MDN they should work with these versions of safari. The code seems to work on desktop, android and other IOS devices (such as the iPhone 12).

On the iPhone X and 6 Plus it throws a Promise error on both of these devices in the console and also doesn't copy to the clipboard:

Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'navigator.clipboard.writeText')

Full error

Has anybody experienced anything similar and has seen / come up with a solution? Thanks!

Code snippet:

   const coupon = couponSelector.value;
    if (notMissing(coupon) && coupon !== '') {
      navigator.clipboard
        .writeText(coupon)
        .then(() =>
          LOGGER.debug({}, `${LOGGER_PREFIX}: Promise Successful.Copied coupon: ${coupon}`),
        )
        .catch((e) => LOGGER.error({ e }, `${LOGGER_PREFIX}: Promise Failed:`));
    }

Upvotes: 9

Views: 12321

Answers (2)

rdela
rdela

Reputation: 666

See my answer on the post linked in Damian Demasi's answer, reproduced here for convenience…

There are security limitations on this API in (Mobile) Safari, one of which is it has to be executed on a site secured with https, so will not work on localhost, for instance:

  • The API is limited to secure contexts, which means that navigator.clipboard is not present for http:// websites.
  • The request to write to the clipboard must be triggered during a user gesture. A call to clipboard.write or clipboard.writeText outside the scope of a user gesture (such as "click" or "touch" event handlers) will result in the immediate rejection of the promise returned by the API call. […]

Upvotes: 18

Damian Demasi
Damian Demasi

Reputation: 81

I had the same problem. Tried different possible solutions, with no success. I ended up using this package: copy-to-clipboard.

Usage:

import copy from 'copy-to-clipboard';
 
copy('Text');

There is a similar problem here, from where I learned about this package.

Upvotes: 4

Related Questions