是否可以在智能手机上触发共享菜单(通过HTML/JS)?

Arm*_*min 44 html javascript android share ios

是否存在通过HTML或JavaScript在智能手机上的本地浏览器中触发共享功能的可能性?

当然,有许多服务提供共享按钮.但是,当我想在Facebook上分享一个网站时,我需要在我目前使用的浏览器中登录到facebook.

几乎所有浏览器都内置了自己的共享功能,触发系统菜单以选择要用于共享的应用程序:

android os中的系统共享菜单

这个问题是关于:如何触发此菜单?

我知道可以在链接的href属性中触发具有指定前缀的电话,例如tel:callto:.也许这个共享菜单的快捷方式也存在?还是一些javascript代码?或者完全不同的方式怎么做?

提前致谢.

aWe*_*per 26

有可能*有很大的收获.目前仅适用于Android的Chrome和桌面游戏.http://caniuse.com/#feat=web-share

if (navigator.share) {
  navigator.share({
    title: document.title,
    text: "Hello World",
    url: window.location.href
  }).then(() => console.log('Successful share'))
  .catch(error => console.log('Error sharing:', error));
}
Run Code Online (Sandbox Code Playgroud)

https://developers.google.com/web/updates/2016/10/navigator-share


mad*_*low 10

据我所知,在移动操作系统的当前浏览器中没有这样的实现.由于这个问题让我感兴趣 - 谷歌搜索显示有朝这个方向做的工作:

对不起 - 我不知道解决方法.


Mac*_*ado 9

我添加了这个,因为所有答案似乎都在2018-07-16之间过时了.

有可能,但仅在少数浏览器(MDN参考)中,通过以下方法中的一个方法API实现navigator:

navigator
    .share({
        title: document.title,
        text: 'Hello World',
        url: window.location.href
    })
    .then(() => console.log('Successful share! '))
    .catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)

Google的参考:https://developers.google.com/web/updates/2016/10/navigator-share

此外,有一个名为Web Intends的东西是一个死的项目,你应该去navigator.share.


gro*_*lex 7

现在可以使用Web Share API 了

但是,到目前为止,它还没有得到广泛的支持。目前,它仅在 Safari(移动和桌面)和 Chrome for Android 中可用。有关详细信息,请参阅我可以使用

根据Introducing the Web Share API on Google Developers,有几点需要牢记:

  • 您的页面需要通过 HTTPS 提供服务
  • 您只能调用navigator.share(…)以响应用户操作,例如单击(即,您不能在页面加载时调用它)
  • 您应该对它进行功能检测,以防它在您的用户平台上不可用(例如,通过navigator.share !== undefined

Google Developers 文章还指出,与 Share API 共享的 URL 不必位于您自己的域中——您可以共享任何 URL。

将所有这些放在一起,您可以使用类似这样的东西,它使用 Share API(如果可用),如果不是*则退回发送电子邮件:

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());
Run Code Online (Sandbox Code Playgroud)

*:请根据您的用例考虑使用更合适的后备(例如,社交共享)。