--- title: Navigator.share slug: Web/API/Navigator/share tags: - Navitator - Share - Web Share translation_of: Web/API/Navigator/share ---
{{APIRef("HTML DOM")}}{{SeeCompatTable}} {{securecontext_header}}

Navigator.share()方法通过调用本机的共享机制作为Web Share API的一部分。如果不支持Web Share API,则此方法为undefined

语法

const sharePromise = window.navigator.share(data);

参数

data
包含要共享的数据的对象。必须至少指定以下字段之一。可用选项包括:

返回值

该方法将会返回一个{{jsxref("Promise")}}。一旦用户完成分享,这个promise将会接受 。如果指定的共享数据格式不正确,promise将会立即拒绝;如果用户取消了分享,promise也会拒绝。

例如, 在Android的Chrome上, 将在用户选择要共享的应用程序后将会解析共享的内容。.

示例

navigator.share({
  title: document.title,
  text: 'Hello World',
  url: 'https://developer.mozilla.org',
}); // 分享MDN的URL

分享文件

分享文件之前,先使用navigator.canShare().判断这个文件能否被分享,Then include an array of files in the call to navigator.share():

Notice: That the sample handles feature detection by testing for navigator.canShare() rather than for navigator.share(). The data object passed to canShare() only supports the files property. Image, video, audio, and text files can be shared.

if (navigator.canShare && navigator.canShare({ files: filesArray })) {
  navigator.share({
    files: filesArray,
    title: 'Pictures',
    text: 'Our Pictures.',
  })
  .then(() => console.log('Share was successful.'))
  .catch((error) => console.log('Sharing failed', error));
} else {
  console.log(`Your system doesn't support sharing files.`);
}

规范

Specification Status Comment
{{SpecName('Web Share API','#share-method','share()')}} {{Spec2('Web Share API')}}

浏览器兼容性

{{Compat("api.Navigator.share")}}

参见