简体   繁体   English

如何在 React 应用程序中实现类似 Wordle 的共享功能?

[英]How can I implement a Wordle-like sharing functionality in a React application?

I'm working on a React (Next.js more specifically) web application and I would like to implement a Worldle-like sharing functionality.我正在开发一个 React(更具体地说是 Next.js)web 应用程序,我想实现一个类似 Worldle 的共享功能。

Here is how it works: when a desktop user clicks a button, I want to copy a string to clipboard and when a mobile user clicks on this button, I want to open up a native sharing screen which would allow users to copy-paste my string into a WhatsApp message, email, Twitter and other social apps.它是这样工作的:当桌面用户点击一个按钮时,我想将一个字符串复制到剪贴板,当移动用户点击这个按钮时,我想打开一个本地共享屏幕,允许用户复制粘贴我的字符串到 WhatsApp 消息、email、Twitter 和其他社交应用程序中。

Copying to clipboard on a desktop is easy enough, I could achieve this using navigator.clipboard.writeText .复制到桌面上的剪贴板非常简单,我可以使用navigator.clipboard.writeText来实现。 This doesn't seem to work on mobile versions of Safari and Chrome, but perhaps I don't even need it to work, instead, I need to somehow open up the sharing screen and I cannot seem to do that.这似乎不适用于 Safari 和 Chrome 的移动版本,但也许我什至不需要它工作,相反,我需要以某种方式打开共享屏幕,但我似乎无法做到这一点。 I've tried using the following click handler:我试过使用以下点击处理程序:

const shareHandler = async () => {
    if ("share" in navigator) {
      await navigator.share({
        title: "Share",
        text: "Share this text",
      })
    } else {
      alert("Share not supported by your browser")
    }
  }

Clicking on my button on a mobile device (iPhone 13) does nothing.在移动设备 (iPhone 13) 上点击我的按钮没有任何反应。 Note that I've used the latest versions of Chrome and Safari, so this should not be caused by obsolete browsers.请注意,我使用的是最新版本的 Chrome 和 Safari,因此这应该不是由过时的浏览器引起的。

Any suggestions on how I could get this working?关于如何使它正常工作的任何建议?

Many thanks!非常感谢!

Update for anyone unfortunate enough to run into a similar issue in the future:任何不幸在未来遇到类似问题的人的更新:

navigator.share can only be used over HTTPS or on localhost. navigator.share只能在 HTTPS 或本地主机上使用。 Since I was trying this on a physical mobile device, I was not on localhost nor was my dev connection served over HTTPS. There are complicated ways in which you can run your server over HTTPS, but I went for a simpler solution, I just used the iOS Simulator which could access my app over localhost.因为我是在物理移动设备上尝试的,所以我不在本地主机上,我的开发连接也不在 HTTPS 上。有多种复杂的方法可以在 HTTPS 上运行服务器,但我选择了一个更简单的解决方案,我只是使用iOS 模拟器,它可以通过本地主机访问我的应用程序。 For a smoother experience, I had to enable developer tools in Safari which allowed me to monitor console logs from the simulator.为了获得更流畅的体验,我必须在 Safari 中启用开发人员工具,这让我可以从模拟器监控控制台日志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM