|
| 1 | +function createShareFile(text: string, filename: string) { |
| 2 | + return new File([text], filename, { type: 'text/plain' }); |
| 3 | +} |
| 4 | + |
| 5 | +export async function shareText( |
| 6 | + title: string, |
| 7 | + text: string, |
| 8 | + filename: string, |
| 9 | + preferShareFile: boolean = false |
| 10 | +) { |
| 11 | + let file; |
| 12 | + try { |
| 13 | + if (navigator.share) { |
| 14 | + let shareData: ShareData = { title, text }; |
| 15 | + if (preferShareFile) { |
| 16 | + file = createShareFile(text, filename); |
| 17 | + const files = [file]; |
| 18 | + if (navigator.canShare && navigator.canShare({ files })) { |
| 19 | + shareData = { ...shareData, text: '', files }; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + await navigator.share(shareData); |
| 24 | + return; |
| 25 | + } |
| 26 | + } catch (error) { |
| 27 | + console.error('Error sharing: ', error); |
| 28 | + } |
| 29 | + |
| 30 | + // if we're here, we failed to share, so we'll try to use the download link |
| 31 | + const shareFile = file ? file : createShareFile(text, filename); |
| 32 | + const url = URL.createObjectURL(shareFile); |
| 33 | + |
| 34 | + const anchor = document.createElement('a'); |
| 35 | + anchor.href = url; |
| 36 | + anchor.download = filename; |
| 37 | + anchor.click(); |
| 38 | + |
| 39 | + URL.revokeObjectURL(url); |
| 40 | +} |
| 41 | + |
| 42 | +export async function shareImage(title: string, text: string, filename: string, image: Blob) { |
| 43 | + const file = new File([image], filename, { type: 'image/png' }); |
| 44 | + try { |
| 45 | + if (navigator.share && navigator.canShare && navigator.canShare({ files: [file] })) { |
| 46 | + const shareData: ShareData = { title, text, files: [file] }; |
| 47 | + |
| 48 | + await navigator.share(shareData); |
| 49 | + return; |
| 50 | + } |
| 51 | + } catch (error) { |
| 52 | + console.error('Error sharing: ', error); |
| 53 | + } |
| 54 | + |
| 55 | + // if we're here, we failed to share, so we'll try to use the download link |
| 56 | + const url = URL.createObjectURL(file); |
| 57 | + |
| 58 | + const anchor = document.createElement('a'); |
| 59 | + anchor.href = url; |
| 60 | + anchor.download = filename; |
| 61 | + anchor.click(); |
| 62 | + |
| 63 | + URL.revokeObjectURL(url); |
| 64 | +} |
0 commit comments