Navigator: canShare() 方法
Navigator 接口的 canShare() 方法会在等效调用 navigator.share() 会成功时返回 true。
当数据无法被验证时,该方法返回 false。数据可能无效的原因包括:
data参数被省略,或者只包含值未知的属性。请注意,用户代理未识别的任何属性都将被忽略。- URL 格式不正确。
- 指定了文件,但实现不支持文件共享。
- 共享指定数据将被用户代理视为“恶意共享”。
Web Share API 受 web-share 权限策略的限制。如果支持该权限但未授予,canShare() 方法将返回 false。
语法
js
canShare()
canShare(data)
参数
返回值
如果指定的数据 data 可以通过 Navigator.share() 进行共享,则返回 true,否则返回 false。
示例
发送 MDN URL
该示例使用 navigator.canShare() 来检查 navigator.share() 是否可以共享指定的数据。
HTML
HTML 仅创建一个段落来显示测试结果。
html
<p class="result"></p>
JavaScript
js
let shareData = {
title: "MDN",
text: "Learn web development on MDN!",
url: "https://mdn.org.cn",
};
const resultPara = document.querySelector(".result");
if (!navigator.canShare) {
resultPara.textContent = "navigator.canShare() not supported.";
} else if (navigator.canShare(shareData)) {
resultPara.textContent =
"navigator.canShare() supported. We can use navigator.share() to send the data.";
} else {
resultPara.textContent = "Specified data cannot be shared.";
}
结果
下方的框应说明此浏览器是否支持 navigator.canShare(),如果支持,我们是否可以使用 navigator.share() 共享指定的数据。
功能检查示例
此方法进行功能测试,以确定特定数据属性是否有效且可共享。如果仅使用单个 data 属性,则仅当该属性有效且可在平台上共享时,它才返回 true。
下面的代码演示了如何验证数据属性是否受支持。
js
// Feature that may not be supported
let testShare = { someNewProperty: "Data to share" };
// Complex data that uses new key
const shareData = {
title: "MDN",
text: "Learn web development on MDN!",
url: "https://mdn.org.cn",
someNewProperty: "Data to share",
};
// Test that the key is valid and supported before sharing
if (navigator.canShare(testShare)) {
// Use navigator.share() to share 'shareData'
} else {
// Handle case that new data property can't be shared.
}
规范
| 规范 |
|---|
| Web Share API # canshare-data-method |
浏览器兼容性
加载中…