feat: add bridge service for mini program web-view integration
- Implemented a bridge utility for sharing, copying links, and setting the navigation bar title in mini program web-view. - Added methods for sharing content and copying links to clipboard. - Included error handling for non-mini program environments.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
82
frontend/src/app/services/bridge.ts
Normal file
82
frontend/src/app/services/bridge.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* 小程序 WebView 桥接工具
|
||||
*
|
||||
* 在 H5(app_03)中调用此工具,可实现分享、复制链接等功能。
|
||||
* 小程序侧(crmeb web_view)通过 @message 监听处理。
|
||||
*
|
||||
* 使用方式:
|
||||
* import bridge from '../services/bridge'
|
||||
*
|
||||
* // 分享给好友
|
||||
* bridge.share({ title: '标题', href: window.location.href })
|
||||
*
|
||||
* // 复制链接
|
||||
* bridge.copyLink(window.location.href)
|
||||
*/
|
||||
|
||||
declare const wx: any
|
||||
|
||||
function getMiniProgram() {
|
||||
try {
|
||||
if (typeof wx !== 'undefined' && wx.miniProgram) {
|
||||
return wx.miniProgram
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const bridge = {
|
||||
postMessage(data: Record<string, any>) {
|
||||
const mp = getMiniProgram()
|
||||
if (mp) {
|
||||
mp.postMessage({ data })
|
||||
} else {
|
||||
console.warn('[bridge] 不在小程序 web-view 环境中')
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 分享给微信好友 / 朋友圈
|
||||
*/
|
||||
share(opts: {
|
||||
title: string
|
||||
href?: string
|
||||
summary?: string
|
||||
imageUrl?: string
|
||||
scene?: 'WXSceneSession' | 'WXSceneTimeline'
|
||||
}) {
|
||||
this.postMessage({
|
||||
action: 'share',
|
||||
title: opts.title || '',
|
||||
href: opts.href || window.location.href,
|
||||
summary: opts.summary || '',
|
||||
imageUrl: opts.imageUrl || '',
|
||||
scene: opts.scene || 'WXSceneSession',
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* 复制链接到剪贴板
|
||||
*/
|
||||
copyLink(link?: string) {
|
||||
this.postMessage({
|
||||
action: 'copyLink',
|
||||
href: link || window.location.href,
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* 设置小程序导航栏标题
|
||||
*/
|
||||
setTitle(title: string) {
|
||||
if (!title) return
|
||||
this.postMessage({
|
||||
action: 'setTitle',
|
||||
title,
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
export default bridge
|
||||
Reference in New Issue
Block a user