Navigator.share() - Web APIs 编辑

Secure context

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

The navigator.share() method of the Web Share API invokes the native sharing mechanism of the device.

Syntax

const sharePromise = navigator.share(data);

Parameters

data
An object containing data to share. At least one of the following fields must be specified. Available options are:
  • url: A USVString representing a URL to be shared.
  • text: A USVString representing text to be shared.
  • title: A USVString representing the title to be shared.
  • files: A "FrozenArray" representing the array of file to be shared.

Return value

A Promise that will be fulfilled once a user has completed a share action (usually the user has chosen an application to share to). It will reject immediately if the data parameter is not correctly specified, and will also reject if the user cancels sharing.

Examples

In our Web share test (see the source code) there is a button which, when clicked, invokes the Web Share API to share MDN's URL. The JavaScript looks like this:

const shareData = {
  title: 'MDN',
  text: 'Learn web development on MDN!',
  url: 'https://developer.mozilla.org',
}

const btn = document.querySelector('button');
const resultPara = document.querySelector('.result');

// Must be triggered some kind of "user activation"
btn.addEventListener('click', async () => {
  try {
    await navigator.share(shareData)
    resultPara.textContent = 'MDN shared successfully'
  } catch(err) {
    resultPara.textContent = 'Error: ' + err
  }
});

Sharing Files

To share files, first test for and call 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.`);
}

Specifications

SpecificationStatusComment
Web Share API
The definition of 'share()' in that specification.
Draft

Browser compatibility

BCD tables only load in the browser

See Also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:105 次

字数:4827

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文