Is it possible to trigger share menu on smartphones (via HTML/JS)?

后端 未结 6 1174
半阙折子戏
半阙折子戏 2020-12-04 21:13

Is there an existing possibility to trigger the share functionality in local browsers on smartphones via HTML or JavaScript?

Of course there are many services which

6条回答
  •  情话喂你
    2020-12-04 21:58

    It's now possible with the Web Share API!

    However, it isn't widely supported as of yet. Currently, it's only available in Safari (mobile and desktop), and Chrome for Android. See Can I Use for details.

    According to Introducing the Web Share API on Google Developers, there are several things to keep in mind:

    • your page needs to be served over HTTPS
    • you can only call navigator.share(…) in response to a user action, such as a click (i.e., you can't call it on page load)
    • you should feature-detect it in case it's not available on your users' platform (e.g., via navigator.share !== undefined)

    The Google Developers article also notes that URLs shared with the Share API need not be on your own domain—you can share any URL.

    Putting that all together, you could use something like this which uses the Share API if it's available, and falls back to sending an email if it's not*:

    function createShareButton() {
      const btn = document.createElement("button");
    
      const title = document.title;
      const text = "Check this out!";
      const url = window.location.href;
    
      btn.innerText = "share" in navigator ? "Share" : "Share via e-mail";
    
      btn.onclick = () => {
        if (navigator.share !== undefined) {
          navigator
            .share({
              title,
              text,
              url
            })
            .then(() => console.log("Shared!"))
            .catch(err => console.error(err));
        } else {
          window.location = `mailto:?subject=${title}&body=${text}%0A${url}`;
        }
      };
    
      return btn;
    }
    
    document.title = "Demo";
    document.body.appendChild(createShareButton());

    *: Please do consider using a more appropriate fallback, (e.g., social sharing) depending on your use case.

提交回复
热议问题