I'm working on a React (Next.js more specifically) web application and I would like to implement a Worldle-like sharing functionality.
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.
Copying to clipboard on a desktop is easy enough, I could achieve this using 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. 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. Note that I've used the latest versions of Chrome and Safari, so this should not be caused by obsolete browsers.
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. 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. For a smoother experience, I had to enable developer tools in Safari which allowed me to monitor console logs from the simulator.