--- title: Navigator.share slug: Web/API/Navigator/share tags: - Navitator - Share - Web Share translation_of: Web/API/Navigator/share ---
Navigator.share()
方法通过调用本机的共享机制作为Web Share API的一部分。如果不支持Web Share API,则此方法为undefined
。
const sharePromise = window.navigator.share(data);
url
: 要共享的URL( {{domxref("USVString")}} )text
: 要共享的文本( {{domxref("USVString")}} )title
: 要共享的标题( {{domxref("USVString")}})files
: 要共享的文件(“FrozenArray”)该方法将会返回一个{{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")}}