Files
lanecarford_front/src/utils/share.ts

210 lines
5.9 KiB
TypeScript
Raw Normal View History

/**
*
* API WhatsApp
*/
interface ShareData {
title?: string
text?: string
url?: string
files?: File[]
}
/**
* Web Share API
*/
export function isWebShareSupported(): boolean {
return typeof navigator !== 'undefined' && 'share' in navigator
}
/**
* 使 Web Share API
* @param data
*/
async function shareWithWebAPI(data: ShareData): Promise<void> {
if (!isWebShareSupported()) {
throw new Error('Web Share API is not supported')
}
try {
// Web Share API 只支持 title, text, url 和 files
const shareData: ShareData = {}
if (data.title) shareData.title = data.title
if (data.text) shareData.text = data.text
if (data.url) shareData.url = data.url
if (data.files && data.files.length > 0) shareData.files = data.files
await navigator.share(shareData)
} catch (error: any) {
// 用户取消分享时,会抛出 AbortError这是正常情况
if (error.name !== 'AbortError') {
console.error('分享失败:', error)
throw error
}
}
}
/**
* WhatsApp退
* @param text
* @param url
*/
export function shareToWhatsApp(text: string, url?: string): void {
const shareText = url ? `${text} ${url}` : text
const encodedText = encodeURIComponent(shareText)
2025-11-27 16:21:50 +08:00
const whatsappScheme = `whatsapp://send?text=${encodedText}`
const whatsappWebUrl = `https://wa.me/?text=${encodedText}`
const isMobile = typeof navigator !== 'undefined' && /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent)
if (typeof window === 'undefined') return
if (isMobile) {
// 优先尝试调用已安装的 WhatsApp 应用,失败后回退到 Web 版本
let didFallback = false
const fallbackTimer = window.setTimeout(() => {
didFallback = true
window.location.href = whatsappWebUrl
}, 1500)
try {
window.location.href = whatsappScheme
} catch (error) {
window.clearTimeout(fallbackTimer)
window.location.href = whatsappWebUrl
}
// 某些浏览器会在成功唤起 App 时终止脚本,无需额外处理
return
}
// 桌面端或不支持 scheme 的环境直接打开 WhatsApp Web
window.open(whatsappWebUrl, '_blank')
}
/**
* 使 Web Share API退 WhatsApp
* @param options
*/
export async function share(options: {
title?: string
text?: string
url?: string
files?: File[]
fallbackToWhatsApp?: boolean
}): Promise<void> {
const { title, text, url, files, fallbackToWhatsApp = true } = options
// 如果支持 Web Share API优先使用
if (isWebShareSupported() && !files) {
try {
await shareWithWebAPI({ title, text, url })
return
} catch (error) {
// 如果分享失败且允许回退,则使用 WhatsApp
if (fallbackToWhatsApp) {
const shareText = [title, text, url].filter(Boolean).join('\n\n')
shareToWhatsApp(shareText)
return
}
throw error
}
}
// 如果不支持 Web Share API 或需要分享文件,使用 WhatsApp
if (fallbackToWhatsApp) {
const shareText = [title, text, url].filter(Boolean).join('\n\n')
shareToWhatsApp(shareText)
} else {
throw new Error('Web Share API is not supported and fallback is disabled')
}
}
/**
* 使退 WhatsApp
* @param title
* @param description
*/
export async function shareCurrentPage(title: string, description?: string): Promise<void> {
const currentUrl = window.location.href
await share({
title,
text: description,
url: currentUrl,
fallbackToWhatsApp: true
})
}
/**
* 使退 WhatsApp
* @param imageUrl
* @param title
* @param description
*/
export async function shareImage(imageUrl: string, title: string, description?: string): Promise<void> {
const currentUrl = window.location.href
const text = description
? `${description}\n\n查看图片: ${imageUrl}`
: `查看图片: ${imageUrl}`
await share({
title,
text,
url: currentUrl,
fallbackToWhatsApp: true
})
}
/**
* 使 Web Share API
* @param imageFile
* @param title
* @param text
*/
export async function shareImageFile(imageFile: File, title?: string, text?: string): Promise<void> {
if (!isWebShareSupported()) {
2025-11-27 15:55:10 +08:00
throw new Error('WEB_SHARE_UNSUPPORTED')
}
2025-11-27 15:55:10 +08:00
if (typeof navigator.canShare === 'function' && !navigator.canShare({ files: [imageFile] })) {
throw new Error('WEB_SHARE_FILE_UNSUPPORTED')
}
2025-11-27 15:55:10 +08:00
await shareWithWebAPI({
title,
text,
files: [imageFile]
})
}
/**
* File 便
* @param imageUrl
* @param fileName
*/
export async function createImageFileFromUrl(imageUrl: string, fileName?: string): Promise<File> {
const response = await fetch(imageUrl)
const blob = await response.blob()
const name = fileName || imageUrl.split('/').pop() || 'share-image.jpg'
return new File([blob], name, { type: blob.type || 'image/jpeg' })
}
/**
* WhatsApp使 shareCurrentPage
* @param title
* @param description
*/
export async function shareCurrentPageToWhatsApp(title: string, description?: string): Promise<void> {
await shareCurrentPage(title, description)
}
/**
* WhatsApp使 shareImage
* @param imageUrl
* @param title
* @param description
*/
export async function shareImageToWhatsApp(imageUrl: string, title: string, description?: string): Promise<void> {
await shareImage(imageUrl, title, description)
}