是否有可能通过 HTML 或 JavaScript 在智能手机上的本地浏览器中触发共享功能?
当然有很多服务提供分享按钮。但是当我例如想要在 facebook 上分享网站,我需要在我当前使用的浏览器中登录 facebook。
几乎所有浏览器都内置了自己的共享功能,该功能会触发系统菜单来选择您要用于共享的应用程序:
这个问题是关于:如何触发这个菜单?
我知道可以通过链接的 href 属性中指定的前缀触发电话,例如
tel:
或 callto:
。也许这个共享菜单的快捷方式也存在?或者一些javascript代码?或者完全不同的方式如何做到这一点?
提前致谢。
有可能有一个大收获。目前仅适用于 Chrome (Android/ChromeOS/Windows)、三星互联网、Edge 和 Safari(桌面/移动)。桌面版 Edge 和 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));
}
https://developers.google.com/web/updates/2016/10/navigator-share
我添加此内容是因为所有答案在 2018 年 7 月 16 日之前似乎都已过时。
这是可能的,但仅限于少数浏览器(MDN 参考),通过
navigator
中的单一方法 API 实现:
navigator
.share({
title: document.title,
text: 'Hello World',
url: window.location.href
})
.then(() => console.log('Successful share! 🎉'))
.catch(err => console.error(err));
Google 的参考:https://developers.google.com/web/updates/2016/10/navigator-share
另外,有一个叫做 Web Intends 的项目,这是一个死项目,你应该选择
navigator.share
来代替。
现在可以使用 Web Share API!
但是,它尚未得到广泛支持。目前,它仅在 Safari(移动和桌面)和 Android 版 Chrome 中可用。详情请参阅我可以使用吗。
根据 Google Developers 上的Introducing the Web Share API,有几件事需要牢记:
navigator.share(…)
来响应用户操作,例如单击(即,您无法在页面加载时调用它)navigator.share !== undefined
)Google 开发者文章还指出,通过 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());
*:请根据您的用例考虑使用更合适的后备方案(例如社交共享)。
2013 年 4 月 10 日回复
据我所知,移动操作系统上的当前浏览器中没有这样的实现。由于我对这个问题感兴趣 - 谷歌搜索显示正在朝这个方向开展工作:
抱歉 - 我不知道解决方法。
这是可能的,我写了一个函数来分享相当多的内容并观察异步副作用:
const shareContact = async (title, content) => {
const text = `${title}
${content}`;
try {
await navigator.share({
text,
});
} catch (e) {
console.log(e);
}
};
您可以使用 Android 的 WebView.addJavascriptInterface() 方法。
首先,您需要编写一个类来激发打开共享菜单的意图(看这里),然后使用 addJavascriptInterface() 调用来实现该类。之后,您需要做的就是从 Javascript 调用该方法。