navigator.share()が使用できない場合はボタンを非表示にしています。
const btn = document.querySelector('button')
const url = 'https://iwb.jp/s/javascript-navigator-share-button/'
const filename = 'sushi.jpg'
if (navigator.canShare) {
const b = document.getElementById('b')
const imgSrc = url + '/' + filename
b.addEventListener('click', () => {
fetch(imgSrc)
.then(res => {
return res.blob()
})
.then(function(blob) {
const file = new File([blob], filename, {type: 'image/jpeg'})
const filesArray = [file]
if(navigator.canShare && navigator.canShare({ files: filesArray })) {
navigator.share({
title: '寿司の画像',
text: 'ネタはマグロや白海老など',
url: url,
files: filesArray,
})
}
})
})
} else {
btn.style.display = 'none'
}