navigator.share
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>navigator.share</title>
</head>
<body>
<!-- <a href="./ji.gif" download="ji.gif">ji.gif</a> -->
<button type="button" class="btn-share">分享</button>
<script>
// navigator.share 呼叫裝置的本機共享機制來共享文字、URL 或檔案等資料
const shareBtn = document.querySelector('.btn-share');
const url = 'https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/canShare';
const shareData = {
title: '這是分享的標題',
// text: '這是分享的文字',
// url: 'https://fastly.picsum.photos/id/924/200/300.jpg?hmac=9Zu3ewQYhI2ltbuwGQk-Ed6PjR87O-zdiPty45pJS6g',
};
shareBtn.addEventListener('click', async () => {
if (!navigator.canShare) {
return alert('當前瀏覽器不支援 navigator.canShare');
}
// const imgBlob = await fetch('./ji.gif').then((res) => res.blob());
// const file = new File([imgBlob], 'share.gif', { type: imgBlob.type });
// shareData.files = [file];
const canShare = navigator.canShare(shareData);
console.log(`支援 navigator.canShare => `, canShare);
if (canShare) {
try {
await navigator.share(shareData);
} catch (err) {
alert('分享失敗' + err);
console.log('share err => ', err);
}
}
});
</script>
</body>
</html>