- Added functionality to open article links in a mini program web-view, allowing users to preview external links. - Implemented mobile hints for external links to improve user experience on mobile devices. - Updated content parser to support new link types, including regular hyperlinks. - Enhanced styling for article links to improve visibility and interaction. Made-with: Cursor
96 lines
2.4 KiB
JavaScript
96 lines
2.4 KiB
JavaScript
const app = getApp()
|
|
|
|
function safeDecode(value) {
|
|
try {
|
|
return decodeURIComponent(value || '')
|
|
} catch (_) {
|
|
return String(value || '')
|
|
}
|
|
}
|
|
|
|
function normalizeHttpUrl(raw) {
|
|
let s = String(raw || '').trim()
|
|
if (!s) return ''
|
|
if (/^\/\//.test(s)) return 'https:' + s
|
|
if (!/^https?:\/\//i.test(s)) s = 'https://' + s.replace(/^\/+/, '')
|
|
return s
|
|
}
|
|
|
|
// 为外链补充移动端提示参数:目标站支持时按手机网页输出
|
|
function appendMobileHints(rawUrl) {
|
|
const url = normalizeHttpUrl(rawUrl)
|
|
if (!url) return ''
|
|
const hasQuery = url.indexOf('?') >= 0
|
|
const hasFrom = /(?:\?|&)from=/i.test(url)
|
|
const hasView = /(?:\?|&)view=/i.test(url)
|
|
const extras = []
|
|
if (!hasFrom) extras.push('from=miniprogram')
|
|
if (!hasView) extras.push('view=mobile')
|
|
if (!extras.length) return url
|
|
return url + (hasQuery ? '&' : '?') + extras.join('&')
|
|
}
|
|
|
|
Page({
|
|
data: {
|
|
url: '',
|
|
title: '链接预览',
|
|
statusBarHeight: 44,
|
|
navBarHeight: 88,
|
|
loadError: false,
|
|
},
|
|
|
|
onLoad(options) {
|
|
const rawUrl = safeDecode(options.url || '')
|
|
const url = appendMobileHints(rawUrl)
|
|
const title = options.title ? safeDecode(options.title) : '链接预览'
|
|
this.setData({
|
|
url,
|
|
title,
|
|
statusBarHeight: app.globalData.statusBarHeight || 44,
|
|
navBarHeight: app.globalData.navBarHeight || 88,
|
|
})
|
|
},
|
|
|
|
onWebViewError() {
|
|
this.setData({ loadError: true })
|
|
wx.showModal({
|
|
title: '无法在小程序内打开',
|
|
content: '该链接无法在小程序内预览,是否复制链接到浏览器打开?',
|
|
confirmText: '复制链接',
|
|
cancelText: '返回',
|
|
success: (res) => {
|
|
if (res.confirm) {
|
|
wx.setClipboardData({
|
|
data: this.data.url,
|
|
success: () => wx.showToast({ title: '链接已复制,请在浏览器打开', icon: 'none', duration: 2000 }),
|
|
})
|
|
} else {
|
|
this.goBack()
|
|
}
|
|
},
|
|
})
|
|
},
|
|
|
|
goBack() {
|
|
const pages = getCurrentPages()
|
|
if (pages.length > 1) {
|
|
wx.navigateBack()
|
|
} else {
|
|
wx.switchTab({ url: '/pages/index/index' })
|
|
}
|
|
},
|
|
|
|
copyLink() {
|
|
const url = (this.data.url || '').trim()
|
|
if (!url) {
|
|
wx.showToast({ title: '暂无可复制链接', icon: 'none' })
|
|
return
|
|
}
|
|
wx.setClipboardData({
|
|
data: url,
|
|
success: () => wx.showToast({ title: '链接已复制', icon: 'none' }),
|
|
})
|
|
},
|
|
})
|
|
|