bridge.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /**
  2. * H5与小程序通信桥接工具函数库
  3. * 提供统一的小程序原生功能调用接口
  4. */
  5. // 全局变量
  6. window.H5_PAGE_NAME = window.H5_PAGE_NAME || 'default'
  7. /**
  8. * 设置当前页面名称
  9. * @param {string} pageName 页面名称
  10. */
  11. function setPageName(pageName) {
  12. window.H5_PAGE_NAME = pageName
  13. }
  14. /**
  15. * 检查微信小程序环境
  16. * @returns {boolean} 是否在微信小程序环境
  17. */
  18. function checkEnvironment() {
  19. return typeof wx !== 'undefined' && wx.miniProgram
  20. }
  21. /**
  22. * 解析URL参数(兼容性处理)
  23. * @param {string} search URL查询字符串
  24. * @returns {Object} 参数对象
  25. */
  26. function parseUrlParams(search) {
  27. const params = {}
  28. if (search) {
  29. search.substring(1).split('&').forEach(param => {
  30. const [key, value] = param.split('=')
  31. if (key && value) {
  32. params[decodeURIComponent(key)] = decodeURIComponent(value)
  33. }
  34. })
  35. }
  36. return params
  37. }
  38. /**
  39. * 检查是否有返回的结果数据
  40. * @param {Function} onResult 结果处理回调
  41. */
  42. function checkResult(onResult) {
  43. const search = window.location.search
  44. console.log('🔍 检查URL参数:', search)
  45. if (search) {
  46. const params = parseUrlParams(search)
  47. console.log('🔍 解析的参数:', params)
  48. if (params.result) {
  49. try {
  50. const resultData = JSON.parse(decodeURIComponent(params.result))
  51. console.log('🔍 解析的结果数据:', resultData)
  52. // 调用回调处理结果
  53. if (onResult) {
  54. onResult(resultData)
  55. }
  56. } catch (error) {
  57. console.error('解析结果数据失败:', error)
  58. }
  59. } else {
  60. console.log('🔍 URL中没有result参数')
  61. }
  62. } else {
  63. console.log('🔍 URL中没有查询参数')
  64. }
  65. }
  66. /**
  67. * 调用小程序原生功能
  68. * @param {string} action 操作类型
  69. * @param {string} message 消息描述
  70. * @param {Object} data 附加数据
  71. */
  72. function callNative(action, message = '', data = null) {
  73. if (!checkEnvironment()) {
  74. console.error('❌ 不在微信小程序环境')
  75. return
  76. }
  77. const params = {
  78. action: action,
  79. message: message || '',
  80. source: window.H5_PAGE_NAME
  81. }
  82. // 处理附加数据
  83. if (data && typeof data === 'object') {
  84. try {
  85. const jsonString = JSON.stringify(data)
  86. params.data = encodeURIComponent(jsonString)
  87. console.log('📦 数据编码:', { original: data, json: jsonString, encoded: params.data })
  88. } catch (error) {
  89. console.error('❌ JSON序列化失败:', error)
  90. return
  91. }
  92. }
  93. // 构建URL参数
  94. const queryParts = []
  95. Object.keys(params).forEach(key => {
  96. if (params[key] !== undefined && params[key] !== null) {
  97. if (key === 'data') {
  98. queryParts.push(`${key}=${params[key]}`)
  99. } else {
  100. queryParts.push(`${key}=${encodeURIComponent(params[key])}`)
  101. }
  102. }
  103. })
  104. const controllerUrl = `/pages/common/h5-controller?${queryParts.join('&')}`
  105. console.log('🎛️ 跳转到控制器:', controllerUrl)
  106. // 调用微信小程序API,添加降级处理
  107. wx.miniProgram.navigateTo({
  108. url: controllerUrl,
  109. success: (res) => {
  110. console.log('✅ 成功跳转到控制器',res)
  111. },
  112. fail: (err) => {
  113. console.error('❌ 控制器调用失败,尝试降级方案:', err)
  114. // 降级方案:使用URL参数通信(兼容老版本webview)
  115. fallbackUrlCommunication(action, message, data)
  116. }
  117. })
  118. }
  119. /**
  120. * 降级通信方案:通过URL参数与webview通信
  121. * @param {string} action 操作类型
  122. * @param {string} message 消息描述
  123. * @param {Object} data 附加数据
  124. */
  125. function fallbackUrlCommunication(action, message = '', data = null) {
  126. console.log('🔄 使用降级通信方案')
  127. const params = {
  128. h5_action: action,
  129. h5_message: message,
  130. timestamp: Date.now()
  131. }
  132. // 如果有额外数据,编码后添加
  133. if (data && typeof data === 'object') {
  134. try {
  135. params.h5_data = encodeURIComponent(JSON.stringify(data))
  136. } catch (error) {
  137. console.error('❌ 数据编码失败:', error)
  138. }
  139. }
  140. // 保留原有的非指令参数
  141. const currentParams = parseUrlParams(window.location.search)
  142. Object.keys(currentParams).forEach(key => {
  143. if (!key.startsWith('h5_') && !key.startsWith('mp_') && key !== 'timestamp') {
  144. params[key] = currentParams[key]
  145. }
  146. })
  147. // 构建新URL
  148. const baseUrl = `${window.location.origin}${window.location.pathname}`
  149. const queryParts = []
  150. Object.keys(params).forEach(key => {
  151. if (params[key] !== undefined && params[key] !== null) {
  152. queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
  153. }
  154. })
  155. const url = `${baseUrl}?${queryParts.join('&')}`
  156. console.log('🔄 降级跳转URL:', url)
  157. // 使用location.href触发webview的load事件
  158. window.location.href = url
  159. }
  160. /**
  161. * 扫码
  162. * @param {string} message 消息描述
  163. * @returns {Promise} 调用结果
  164. */
  165. function scanCode(message = '扫描二维码') {
  166. return callNative('scanCode', message)
  167. }
  168. /**
  169. * 选择图片
  170. * @param {string} message 消息描述
  171. * @returns {Promise} 调用结果
  172. */
  173. function chooseImage(message = '选择图片') {
  174. return callNative('chooseImage', message)
  175. }
  176. /**
  177. * 拨打电话
  178. * @param {string} phoneNumber 电话号码
  179. * @param {string} message 消息描述
  180. * @returns {Promise} 调用结果
  181. */
  182. function makePhoneCall(phoneNumber, message = '拨打电话') {
  183. return callNative('makePhoneCall', message, { phoneNumber })
  184. }
  185. /**
  186. * 设置存储
  187. * @param {string} key 存储键
  188. * @param {*} value 存储值
  189. * @param {string} message 消息描述
  190. * @returns {Promise} 调用结果
  191. */
  192. function setStorage(key, value, message = '设置存储数据') {
  193. return callNative('setStorage', message, { key, value })
  194. }
  195. /**
  196. * 获取存储
  197. * @param {string} key 存储键
  198. * @param {string} message 消息描述
  199. * @returns {Promise} 调用结果
  200. */
  201. function getStorage(key, message = '获取存储数据') {
  202. return callNative('getStorage', message, { key })
  203. }
  204. /**
  205. * 返回小程序
  206. * @param {string} message 消息描述
  207. * @returns {Promise} 调用结果
  208. */
  209. function goBack(message = '返回小程序') {
  210. return callNative('goBack', message)
  211. }
  212. /**
  213. * 页面跳转
  214. * @param {string} page 目标页面
  215. * @param {Object} params 跳转参数
  216. */
  217. function navigateTo(page, params = {}) {
  218. const queryString = Object.keys(params).length > 0
  219. ? '?' + Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&')
  220. : ''
  221. window.location.href = `./${page}.html${queryString}`
  222. }
  223. /**
  224. * 保存数据到localStorage
  225. * @param {string} key 存储键
  226. * @param {*} data 存储数据
  227. */
  228. function saveData(key, data) {
  229. try {
  230. const storageKey = `h5_${window.H5_PAGE_NAME}_${key}`
  231. localStorage.setItem(storageKey, JSON.stringify(data))
  232. console.log('💾 数据已保存:', storageKey)
  233. } catch (error) {
  234. console.error('保存数据失败:', error)
  235. }
  236. }
  237. /**
  238. * 从localStorage加载数据
  239. * @param {string} key 存储键
  240. * @param {*} defaultValue 默认值
  241. * @returns {*} 加载的数据
  242. */
  243. function loadData(key, defaultValue = null) {
  244. try {
  245. const storageKey = `h5_${window.H5_PAGE_NAME}_${key}`
  246. const savedData = localStorage.getItem(storageKey)
  247. if (savedData) {
  248. return JSON.parse(savedData)
  249. }
  250. } catch (error) {
  251. console.error('加载数据失败:', error)
  252. }
  253. return defaultValue
  254. }
  255. /**
  256. * 清除保存的数据
  257. * @param {string} key 存储键
  258. */
  259. function clearData(key) {
  260. try {
  261. const storageKey = `h5_${window.H5_PAGE_NAME}_${key}`
  262. localStorage.removeItem(storageKey)
  263. console.log('🗑️ 数据已清除:', storageKey)
  264. } catch (error) {
  265. console.error('清除数据失败:', error)
  266. }
  267. }
  268. /**
  269. * 默认的结果处理函数
  270. * @param {Object} data 结果数据
  271. */
  272. function defaultResultHandler(data) {
  273. const { action, success, result, error } = data
  274. if (success) {
  275. console.log(`✅ ${action} 操作成功`, result)
  276. } else {
  277. console.error(`❌ ${action} 操作失败`, error)
  278. }
  279. }
  280. /**
  281. * 初始化页面(可选调用)
  282. * @param {string} pageName 页面名称
  283. * @param {Function} onResult 结果处理回调,不传则使用默认处理
  284. */
  285. function initPage(pageName, onResult) {
  286. setPageName(pageName)
  287. checkEnvironment()
  288. // 如果没有提供自定义处理,使用默认处理
  289. const resultHandler = onResult || defaultResultHandler
  290. checkResult(resultHandler)
  291. }
  292. // ==================== UI工具函数 ====================
  293. /**
  294. * 显示Toast效果(H5页面UI)
  295. * @param {string} message Toast消息
  296. * @param {number} duration 显示时长(毫秒)
  297. * @param {string} type 类型:success|error|warning|info
  298. */
  299. function showToastEffect(message, duration = 2000, type = 'success') {
  300. const colors = {
  301. success: 'rgba(40, 167, 69, 0.9)',
  302. error: 'rgba(220, 53, 69, 0.9)',
  303. warning: 'rgba(255, 193, 7, 0.9)',
  304. info: 'rgba(23, 162, 184, 0.9)'
  305. }
  306. const toast = document.createElement('div')
  307. toast.textContent = message
  308. toast.style.cssText = `
  309. position: fixed;
  310. top: 50%;
  311. left: 50%;
  312. transform: translate(-50%, -50%);
  313. background: ${colors[type] || colors.success};
  314. color: white;
  315. padding: 12px 24px;
  316. border-radius: 8px;
  317. z-index: 9999;
  318. font-size: 14px;
  319. pointer-events: none;
  320. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  321. `
  322. document.body.appendChild(toast)
  323. setTimeout(() => {
  324. if (toast.parentNode) {
  325. toast.parentNode.removeChild(toast)
  326. }
  327. }, duration)
  328. }
  329. /**
  330. * 显示加载中效果
  331. * @param {string} message 加载消息
  332. * @returns {Function} 关闭加载的函数
  333. */
  334. function showLoading(message = '加载中...') {
  335. const loading = document.createElement('div')
  336. loading.innerHTML = `
  337. <div style="
  338. display: flex;
  339. align-items: center;
  340. justify-content: center;
  341. flex-direction: column;
  342. color: white;
  343. ">
  344. <div style="
  345. width: 30px;
  346. height: 30px;
  347. border: 3px solid rgba(255, 255, 255, 0.3);
  348. border-top: 3px solid white;
  349. border-radius: 50%;
  350. animation: spin 1s linear infinite;
  351. margin-bottom: 12px;
  352. "></div>
  353. <div>${message}</div>
  354. </div>
  355. `
  356. loading.style.cssText = `
  357. position: fixed;
  358. top: 0;
  359. left: 0;
  360. width: 100%;
  361. height: 100%;
  362. background: rgba(0, 0, 0, 0.7);
  363. display: flex;
  364. align-items: center;
  365. justify-content: center;
  366. z-index: 10000;
  367. font-size: 14px;
  368. `
  369. // 添加旋转动画
  370. if (!document.querySelector('#loading-style')) {
  371. const style = document.createElement('style')
  372. style.id = 'loading-style'
  373. style.textContent = `
  374. @keyframes spin {
  375. 0% { transform: rotate(0deg); }
  376. 100% { transform: rotate(360deg); }
  377. }
  378. `
  379. document.head.appendChild(style)
  380. }
  381. document.body.appendChild(loading)
  382. return function closeLoading() {
  383. if (loading.parentNode) {
  384. loading.parentNode.removeChild(loading)
  385. }
  386. }
  387. }
  388. /**
  389. * 格式化日期
  390. * @param {Date|string|number} date 日期
  391. * @param {string} format 格式
  392. * @returns {string} 格式化后的日期
  393. */
  394. function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  395. const d = new Date(date)
  396. const year = d.getFullYear()
  397. const month = String(d.getMonth() + 1).padStart(2, '0')
  398. const day = String(d.getDate()).padStart(2, '0')
  399. const hours = String(d.getHours()).padStart(2, '0')
  400. const minutes = String(d.getMinutes()).padStart(2, '0')
  401. const seconds = String(d.getSeconds()).padStart(2, '0')
  402. return format
  403. .replace('YYYY', year)
  404. .replace('MM', month)
  405. .replace('DD', day)
  406. .replace('HH', hours)
  407. .replace('mm', minutes)
  408. .replace('ss', seconds)
  409. }