Navigator.share

翻译不完整。 请帮助我们翻译这篇文章!

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

Secure context
This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

语法

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

参数

data
包含要共享的数据的对象。必须至少指定以下字段之一。可用选项包括:
  • url: 要共享的URL( USVString
  • text: 要共享的文本( USVString
  • title: 要共享的标题( USVString
  • files: 要共享的文件(“FrozenArray”)

返回值

该方法将会返回一个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
Web Share API
share()
Draft

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
share
Experimental
Chrome No support NoEdge Full support 81Firefox No support NoIE No support NoOpera No support NoSafari Full support 12.1WebView Android No support NoChrome Android Full support 61Firefox Android No support NoOpera Android Full support 48Safari iOS Full support 12.2Samsung Internet Android Full support 8.0

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.

参见