Safari clipboard error "TypeError: undefined is not an object"
Asked Answered
S

2

10

Have an error only in safari browser:

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

I'm passing my current link. What could be the problem?

copyLink = e => {
  e.preventDefault();
  console.log(document.location.href)
  navigator.clipboard
    .writeText(document.location.href)
    .then(() => {
      this.setState({
        urlIsCopied: true
      });
    })
    .catch(e => console.error(e));
};
Surveyor answered 10/9, 2019 at 10:2 Comment(4)
The status in Safari for this API unknown probably not supported developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboardDesalvo
Always search if API can be used in browser you need to support (check Can I use not sure what one is the API you need). for browsers that don't support the API you need different solution.Desalvo
I have this error which popped up in Sentry, on Safari 14, where it's supposed to be supported. I suspect it's disabled in private browsing...Luvenialuwana
@Luvenialuwana Same here, Sentry, Safari 15.2. Tested and working in private browsing, though...Subsonic
R
2

Can you please look at the plugin copy-to-clipboard. Simply use below code and it works.

copy('Text to Copy!');

Hope this will help you!

Recount answered 10/9, 2019 at 10:11 Comment(0)
H
11

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. […]
Hibernate answered 19/6, 2022 at 19:30 Comment(1)
R
2

Can you please look at the plugin copy-to-clipboard. Simply use below code and it works.

copy('Text to Copy!');

Hope this will help you!

Recount answered 10/9, 2019 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.