| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464 |
- /**
- * H5版本的页面导航工具
- * 提供统一的页面跳转、返回、刷新等功能
- */
- /**
- * 页面导航管理器
- */
- const NAV_IGNORED_KEYS = new Set([
- "function",
- "pageList",
- "pluginList",
- "children",
- "options",
- ]);
- const LIST_RETURN_REFRESH_KEY = "_mp_list_return_refresh";
- function normalizeLocalPageUrl(value) {
- const text = String(value || "").trim();
- if (!text) return null;
- try {
- const url = new URL(text, window.location.href);
- if (url.origin !== window.location.origin) return null;
- if (!/^\/page\/mp\/[^/]+\.html$/i.test(url.pathname)) return null;
- return url;
- } catch (_) {
- return null;
- }
- }
- function isListPageUrl(url) {
- if (!(url instanceof URL)) return false;
- return /_list\.html$/i.test(url.pathname)
- || /\/mp_objList\.html$/i.test(url.pathname);
- }
- function readReferrerUrl() {
- const referrer = String(document.referrer || "").trim();
- if (!referrer) return null;
- try {
- const url = new URL(referrer, window.location.href);
- return url.origin === window.location.origin ? url : null;
- } catch (_) {
- return null;
- }
- }
- function writeSessionValues(values) {
- Object.entries(values || {}).forEach(([key, value]) => {
- if (value === undefined || value === null || value === "") return;
- try {
- sessionStorage.setItem(key, String(value));
- } catch (_) {}
- });
- }
- 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]));
- }
- });
- const currentUrl = normalizeLocalPageUrl(window.location.href);
- if (currentUrl && isListPageUrl(currentUrl)) {
- urlParams.set('returnTo', currentUrl.href);
- }
-
- // 添加导航标记,用于返回时刷新
- 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';
- const referrer = readReferrerUrl();
- const listTarget = normalizeLocalPageUrl(
- options.listPage || urlParams.get("returnTo")
- ) || (isListPageUrl(referrer) ? referrer : null);
-
- if (needRefresh && options.refreshParent !== false) {
- // 通知父页面刷新
- this.notifyParentRefresh();
- if (listTarget)
- this.markListRefresh(listTarget.href, options.refreshData || {});
- }
-
- // 返回上一页
- if (window.history.length > 1) {
- window.history.back();
- } else {
- const returnTo = listTarget;
- if (returnTo) {
- window.location.replace(returnTo.href);
- } else if (window.wx && window.wx.miniProgram
- && typeof window.wx.miniProgram.navigateBack === "function") {
- window.wx.miniProgram.navigateBack({ delta: 1 });
- }
- }
-
- } catch (error) {
- console.error('❌ 页面返回失败:', error);
- if (typeof showToast !== 'undefined') {
- showToast('页面返回失败', 'error');
- }
- }
- },
- /**
- * 提交成功后生成列表刷新标记。
- */
- markListRefresh(listPage, data = {}, storageValues = {}) {
- const target = normalizeLocalPageUrl(listPage);
- if (!target) return null;
- const payload = {
- listUrl: target.href,
- timestamp: Date.now(),
- data: data && typeof data === "object" ? data : {},
- };
- try {
- sessionStorage.setItem(LIST_RETURN_REFRESH_KEY, JSON.stringify(payload));
- } catch (_) {}
- writeSessionValues(storageValues);
- return payload;
- },
- /**
- * 列表页在 pageshow/visibilitychange 时消费刷新标记。
- */
- consumeListRefresh(currentUrl = window.location.href) {
- const current = normalizeLocalPageUrl(currentUrl);
- if (!current) return null;
- let record = null;
- try {
- const raw = sessionStorage.getItem(LIST_RETURN_REFRESH_KEY) || "";
- record = raw ? JSON.parse(raw) : null;
- } catch (_) {
- return null;
- }
- const target = normalizeLocalPageUrl(record && record.listUrl);
- if (!target || target.pathname !== current.pathname) return null;
- try {
- sessionStorage.removeItem(LIST_RETURN_REFRESH_KEY);
- } catch (_) {}
- return record && record.data && typeof record.data === "object"
- ? record.data
- : {};
- },
- /**
- * 录入页提交成功后返回列表。
- * 来源确为同一列表时使用 H5 历史返回;直接进入录入页时明确跳转列表。
- */
- returnToList(listPage, options = {}) {
- const referrer = readReferrerUrl();
- const target = normalizeLocalPageUrl(listPage)
- || (isListPageUrl(referrer) ? referrer : null);
- if (!target) {
- this.goBack({ refreshParent: true });
- return false;
- }
- const canUseHistory = window.history.length > 1
- && !!referrer
- && referrer.pathname === target.pathname;
- if (canUseHistory) {
- this.markListRefresh(
- target.href,
- options.refreshData || {},
- options.storageValues || {}
- );
- window.history.back();
- return true;
- }
- window.location.replace(target.href);
- return true;
- },
- /**
- * 通知父页面刷新(通过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);
- window.returnToList = NavigationManager.returnToList.bind(NavigationManager);
- console.log('✅ H5页面导航工具加载完成');
|