Navigator: canShare() 方法

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

Navigator 接口的 canShare() 方法会在等效调用 navigator.share() 会成功时返回 true

当数据无法被验证时,该方法返回 false。数据可能无效的原因包括:

  • data 参数被省略,或者只包含值未知的属性。请注意,用户代理未识别的任何属性都将被忽略。
  • URL 格式不正确。
  • 指定了文件,但实现不支持文件共享。
  • 共享指定数据将被用户代理视为“恶意共享”。

Web Share APIweb-share 权限策略的限制。如果支持该权限但未授予,canShare() 方法将返回 false

语法

js
canShare()
canShare(data)

参数

data 可选

一个定义要测试的共享数据的对象。通常,如果此调用返回 true,则会将具有相同属性的对象传递给 navigator.share()

用户代理未知的属性将被忽略;共享数据仅根据用户代理理解的属性进行评估。所有属性都是可选的,但必须指定至少一个已知的属性,否则方法将返回 false

可能的值是

url 可选

一个表示要共享的 URL 的字符串。

text 可选

一个表示要共享的文本的字符串。

title 可选

一个表示要共享的标题的字符串。

files 可选

一个表示要共享的文件的 File 对象数组。

返回值

如果指定的数据 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

浏览器兼容性

另见