/** * H5版本的页面导航工具 * 提供统一的页面跳转、返回、刷新等功能 */ /** * 页面导航管理器 */ const NAV_IGNORED_KEYS = new Set([ "function", "pageList", "pluginList", "children", "options", ]); function pickPrimitiveParams(source = {}) { const result = {}; Object.entries(source).forEach(([key, value]) => { if (NAV_IGNORED_KEYS.has(key)) return; if (value === undefined || value === null || value === "") return; const type = typeof value; if (type === "string" || type === "number" || type === "boolean") { result[key] = value; } }); return result; } function normalizeParamScalar(value) { if (value === undefined || value === null) return ""; const text = String(value).trim(); if (!text) return ""; if ( (text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'")) ) { return text.slice(1, -1); } return text; } function mergeParamPayload(target, rawValue) { if (rawValue === undefined || rawValue === null || rawValue === "") return; if (typeof rawValue === "object" && !Array.isArray(rawValue)) { Object.entries(rawValue).forEach(([key, value]) => { if (value === undefined || value === null || value === "") return; const type = typeof value; if (type === "string" || type === "number" || type === "boolean") { target[key] = value; } }); return; } if (typeof rawValue !== "string") return; const text = rawValue.trim(); if (!text) return; try { const parsed = JSON.parse(text); if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { mergeParamPayload(target, parsed); return; } } catch (_) {} text.split(",").forEach((segment) => { const part = String(segment || "").trim(); if (!part) return; const separatorIndex = part.indexOf(":"); if (separatorIndex <= 0) return; const key = normalizeParamScalar(part.slice(0, separatorIndex)); const value = normalizeParamScalar(part.slice(separatorIndex + 1)); if (!key || !value) return; target[key] = value; }); } const NavigationManager = { /** * 跳转到目标页面 * @param {string} destPage - 目标页面名称(不含.html) * @param {object} params - 传递的参数 * @param {object} options - 跳转选项 */ goTo(destPage, params = {}, options = {}) { try { const urlParams = new URLSearchParams(window.location.search); // 添加新参数 Object.keys(params).forEach(key => { if (params[key] !== undefined && params[key] !== null) { urlParams.set(key, encodeURIComponent(params[key])); } }); // 添加导航标记,用于返回时刷新 if (options.needRefresh) { urlParams.set('_needRefresh', '1'); } // 构建目标URL const newUrl = `${destPage}.html?${urlParams.toString()}`; console.log('🔗 导航到:', newUrl); console.log('📋 传递参数:', Object.fromEntries(urlParams)); // 跳转页面 window.location.href = newUrl; } catch (error) { console.error('❌ 页面导航失败:', error); if (typeof showToast !== 'undefined') { showToast('页面跳转失败', 'error'); } else { alert('页面跳转失败'); } } }, /** * 处理buttonList按钮跳转 * @param {object} button - 按钮配置 */ goToFromButton(button) { // 优先检查function.dest,然后是button.dest const buttonConfig = button && typeof button === "object" ? button : {}; const functionConfig = buttonConfig.function && typeof buttonConfig.function === "object" ? buttonConfig.function : {}; const rawDestPage = functionConfig.dest || buttonConfig.dest; // 功能说明:后端返回 dest(如 objInp)时自动补齐 mp_ 前缀,统一跳转到移动端页面 by xu 2026-02-28 const destPage = (() => { const target = String(rawDestPage || '').trim(); if (!target) return ''; if (target.startsWith('mp_')) return target; return `mp_${target}`; })(); console.log("goToFromButton:",destPage) if (!destPage) { console.warn('按钮没有配置跳转页面:', button); return false; } const params = { ...pickPrimitiveParams(buttonConfig), ...pickPrimitiveParams(functionConfig), dest: String(rawDestPage || "").trim(), ssDest: String(rawDestPage || "").trim(), title: functionConfig.desc || functionConfig.title || buttonConfig.desc || buttonConfig.title || buttonConfig.buttonName || buttonConfig.name || "", service: functionConfig.servName || buttonConfig.servName || buttonConfig.service || "" }; mergeParamPayload(params, buttonConfig.param); mergeParamPayload(params, functionConfig.param); mergeParamPayload(params, buttonConfig.parm); mergeParamPayload(params, functionConfig.parm); const paramName = String( functionConfig.param_name || buttonConfig.param_name || "" ).trim(); const paramValue = functionConfig.param_value !== undefined ? functionConfig.param_value : buttonConfig.param_value; if ( paramName && paramValue !== undefined && paramValue !== null && paramValue !== "" ) { params[paramName] = paramValue; } // 跳转页面,标记需要刷新 this.goTo(destPage, params, { needRefresh: true }); return true; }, /** * 返回上一页 * @param {object} options - 返回选项 */ goBack(options = {}) { try { // 检查是否需要刷新父页面 const urlParams = new URLSearchParams(window.location.search); const needRefresh = urlParams.get('_needRefresh') === '1'; if (needRefresh && options.refreshParent !== false) { // 通知父页面刷新 this.notifyParentRefresh(); } // 返回上一页 if (window.history.length > 1) { window.history.back(); } else { NavigationManager.goBack() } } catch (error) { console.error('❌ 页面返回失败:', error); if (typeof showToast !== 'undefined') { showToast('页面返回失败', 'error'); } } }, /** * 通知父页面刷新(通过localStorage) */ notifyParentRefresh() { try { const refreshData = { timestamp: Date.now(), action: 'refresh', source: window.location.pathname }; localStorage.setItem('_pageRefreshNotify', JSON.stringify(refreshData)); // 触发storage事件 window.dispatchEvent(new StorageEvent('storage', { key: '_pageRefreshNotify', newValue: JSON.stringify(refreshData) })); console.log('📢 通知父页面刷新'); } catch (error) { console.error('❌ 通知父页面刷新失败:', error); } }, /** * 监听页面刷新通知 * @param {function} callback - 刷新回调函数 */ onRefreshNotify(callback) { if (typeof callback !== 'function') { console.warn('刷新回调必须是函数'); return; } // 监听localStorage变化 const handleStorageChange = (event) => { if (event.key === '_pageRefreshNotify' && event.newValue) { try { const refreshData = JSON.parse(event.newValue); console.log('📢 收到页面刷新通知:', refreshData); // 执行刷新回调 callback(refreshData); // 清除通知 localStorage.removeItem('_pageRefreshNotify'); } catch (error) { console.error('❌ 处理刷新通知失败:', error); } } }; window.addEventListener('storage', handleStorageChange); // 返回清理函数 return () => { window.removeEventListener('storage', handleStorageChange); }; }, /** * 刷新当前页面数据 * @param {function} refreshCallback - 刷新数据的回调函数 */ refreshCurrentPage(refreshCallback) { if (typeof refreshCallback === 'function') { console.log('🔄 刷新当前页面数据'); refreshCallback(); } else { // 默认刷新整个页面 window.location.reload(); } }, /** * 获取URL参数 * @param {string} key - 参数名,不传则返回所有参数 * @returns {string|object} 参数值或参数对象 */ getUrlParam(key) { const urlParams = new URLSearchParams(window.location.search); if (key) { const value = urlParams.get(key); return value ? decodeURIComponent(value) : null; } // 返回所有参数 const params = {}; for (const [paramKey, paramValue] of urlParams) { params[paramKey] = decodeURIComponent(paramValue); } return params; } }; // 导出到全局 window.NavigationManager = NavigationManager; // 兼容性:也导出为全局函数 window.goTo = NavigationManager.goTo.bind(NavigationManager); window.goBack = NavigationManager.goBack.bind(NavigationManager); window.getUrlParam = NavigationManager.getUrlParam.bind(NavigationManager); console.log('✅ H5页面导航工具加载完成');