| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334 |
- /**
- * 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页面导航工具加载完成');
|