最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Safari clipboard error "TypeError: undefined is not an object" - Stack Overflow

programmeradmin1浏览0评论

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));
};

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));
};
Share Improve this question edited Feb 11, 2023 at 18:20 Tyler2P 2,37030 gold badges25 silver badges32 bronze badges asked Sep 10, 2019 at 10:02 Yerlan YeszhanovYerlan Yeszhanov 2,43912 gold badges42 silver badges78 bronze badges 4
  • The status in Safari for this API unknown probably not supported developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard – jcubic Commented Sep 10, 2019 at 10:06
  • 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. – jcubic Commented Sep 10, 2019 at 10:08
  • 1 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... – vcarel Commented Nov 5, 2021 at 8:58
  • 1 @vcarel Same here, Sentry, Safari 15.2. Tested and working in private browsing, though... – sheng Commented Feb 7, 2022 at 5:39
Add a comment  | 

2 Answers 2

Reset to default 14

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. […]

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!

发布评论

评论列表(0)

  1. 暂无评论