xinli/xinlidsj/utils/link.js

80 lines
1.9 KiB
JavaScript
Raw Normal View History

2026-02-24 16:49:05 +08:00
import { getBaseUrl } from './config'
function isHttpUrl(url) {
return /^https?:\/\//i.test(url)
}
function isPageUrl(url) {
return typeof url === 'string' && url.startsWith('/pages/')
}
function isFileUrl(url) {
return /\.(pdf|doc|docx|xls|xlsx|ppt|pptx)$/i.test(url || '')
}
function toWsUrl(baseUrl) {
if (!baseUrl) return ''
return baseUrl.replace(/^https?:\/\//i, (m) => (m.toLowerCase() === 'https://' ? 'wss://' : 'ws://'))
}
export function openLink(linkUrl, options = {}) {
const url = (linkUrl || '').trim()
if (!url) {
uni.showToast({ title: '链接为空', icon: 'none' })
return
}
if (isPageUrl(url)) {
uni.navigateTo({ url })
return
}
if (isHttpUrl(url)) {
if (isFileUrl(url)) {
uni.showLoading({ title: '正在打开...' })
uni.downloadFile({
url,
success: (res) => {
if (res.statusCode !== 200) {
uni.hideLoading()
uni.showToast({ title: '下载失败', icon: 'none' })
return
}
uni.openDocument({
filePath: res.tempFilePath,
showMenu: true,
success: () => {
uni.hideLoading()
},
fail: () => {
uni.hideLoading()
uni.showToast({ title: '无法打开文件', icon: 'none' })
}
})
},
fail: () => {
uni.hideLoading()
uni.showToast({ title: '下载失败', icon: 'none' })
}
})
return
}
const encoded = encodeURIComponent(url)
const title = options.title ? encodeURIComponent(options.title) : ''
const page = `/pages/webview/index?url=${encoded}${title ? `&title=${title}` : ''}`
uni.navigateTo({ url: page })
return
}
uni.showToast({ title: '不支持的链接格式', icon: 'none' })
}
export function getMessageWsUrl(token) {
const baseUrl = getBaseUrl()
const wsBase = toWsUrl(baseUrl)
if (!wsBase) return ''
const t = (token || '').trim()
return `${wsBase}/ws/message${t ? `?token=${encodeURIComponent(t)}` : ''}`
}