navigation.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /**
  2. * H5版本的页面导航工具
  3. * 提供统一的页面跳转、返回、刷新等功能
  4. */
  5. /**
  6. * 页面导航管理器
  7. */
  8. const NAV_IGNORED_KEYS = new Set([
  9. "function",
  10. "pageList",
  11. "pluginList",
  12. "children",
  13. "options",
  14. ]);
  15. const LIST_RETURN_REFRESH_KEY = "_mp_list_return_refresh";
  16. function normalizeLocalPageUrl(value) {
  17. const text = String(value || "").trim();
  18. if (!text) return null;
  19. try {
  20. const url = new URL(text, window.location.href);
  21. if (url.origin !== window.location.origin) return null;
  22. if (!/^\/page\/mp\/[^/]+\.html$/i.test(url.pathname)) return null;
  23. return url;
  24. } catch (_) {
  25. return null;
  26. }
  27. }
  28. function isListPageUrl(url) {
  29. if (!(url instanceof URL)) return false;
  30. return /_list\.html$/i.test(url.pathname)
  31. || /\/mp_objList\.html$/i.test(url.pathname);
  32. }
  33. function readReferrerUrl() {
  34. const referrer = String(document.referrer || "").trim();
  35. if (!referrer) return null;
  36. try {
  37. const url = new URL(referrer, window.location.href);
  38. return url.origin === window.location.origin ? url : null;
  39. } catch (_) {
  40. return null;
  41. }
  42. }
  43. function writeSessionValues(values) {
  44. Object.entries(values || {}).forEach(([key, value]) => {
  45. if (value === undefined || value === null || value === "") return;
  46. try {
  47. sessionStorage.setItem(key, String(value));
  48. } catch (_) {}
  49. });
  50. }
  51. function pickPrimitiveParams(source = {}) {
  52. const result = {};
  53. Object.entries(source).forEach(([key, value]) => {
  54. if (NAV_IGNORED_KEYS.has(key)) return;
  55. if (value === undefined || value === null || value === "") return;
  56. const type = typeof value;
  57. if (type === "string" || type === "number" || type === "boolean") {
  58. result[key] = value;
  59. }
  60. });
  61. return result;
  62. }
  63. function normalizeParamScalar(value) {
  64. if (value === undefined || value === null) return "";
  65. const text = String(value).trim();
  66. if (!text) return "";
  67. if (
  68. (text.startsWith('"') && text.endsWith('"')) ||
  69. (text.startsWith("'") && text.endsWith("'"))
  70. ) {
  71. return text.slice(1, -1);
  72. }
  73. return text;
  74. }
  75. function mergeParamPayload(target, rawValue) {
  76. if (rawValue === undefined || rawValue === null || rawValue === "") return;
  77. if (typeof rawValue === "object" && !Array.isArray(rawValue)) {
  78. Object.entries(rawValue).forEach(([key, value]) => {
  79. if (value === undefined || value === null || value === "") return;
  80. const type = typeof value;
  81. if (type === "string" || type === "number" || type === "boolean") {
  82. target[key] = value;
  83. }
  84. });
  85. return;
  86. }
  87. if (typeof rawValue !== "string") return;
  88. const text = rawValue.trim();
  89. if (!text) return;
  90. try {
  91. const parsed = JSON.parse(text);
  92. if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
  93. mergeParamPayload(target, parsed);
  94. return;
  95. }
  96. } catch (_) {}
  97. text.split(",").forEach((segment) => {
  98. const part = String(segment || "").trim();
  99. if (!part) return;
  100. const separatorIndex = part.indexOf(":");
  101. if (separatorIndex <= 0) return;
  102. const key = normalizeParamScalar(part.slice(0, separatorIndex));
  103. const value = normalizeParamScalar(part.slice(separatorIndex + 1));
  104. if (!key || !value) return;
  105. target[key] = value;
  106. });
  107. }
  108. const NavigationManager = {
  109. /**
  110. * 跳转到目标页面
  111. * @param {string} destPage - 目标页面名称(不含.html)
  112. * @param {object} params - 传递的参数
  113. * @param {object} options - 跳转选项
  114. */
  115. goTo(destPage, params = {}, options = {}) {
  116. try {
  117. const urlParams = new URLSearchParams(window.location.search);
  118. // 添加新参数
  119. Object.keys(params).forEach(key => {
  120. if (params[key] !== undefined && params[key] !== null) {
  121. urlParams.set(key, encodeURIComponent(params[key]));
  122. }
  123. });
  124. const currentUrl = normalizeLocalPageUrl(window.location.href);
  125. if (currentUrl && isListPageUrl(currentUrl)) {
  126. urlParams.set('returnTo', currentUrl.href);
  127. }
  128. // 添加导航标记,用于返回时刷新
  129. if (options.needRefresh) {
  130. urlParams.set('_needRefresh', '1');
  131. }
  132. // 构建目标URL
  133. const newUrl = `${destPage}.html?${urlParams.toString()}`;
  134. console.log('🔗 导航到:', newUrl);
  135. console.log('📋 传递参数:', Object.fromEntries(urlParams));
  136. // 跳转页面
  137. window.location.href = newUrl;
  138. } catch (error) {
  139. console.error('❌ 页面导航失败:', error);
  140. if (typeof showToast !== 'undefined') {
  141. showToast('页面跳转失败', 'error');
  142. } else {
  143. alert('页面跳转失败');
  144. }
  145. }
  146. },
  147. /**
  148. * 处理buttonList按钮跳转
  149. * @param {object} button - 按钮配置
  150. */
  151. goToFromButton(button) {
  152. // 优先检查function.dest,然后是button.dest
  153. const buttonConfig =
  154. button && typeof button === "object" ? button : {};
  155. const functionConfig =
  156. buttonConfig.function && typeof buttonConfig.function === "object"
  157. ? buttonConfig.function
  158. : {};
  159. const rawDestPage = functionConfig.dest || buttonConfig.dest;
  160. // 功能说明:后端返回 dest(如 objInp)时自动补齐 mp_ 前缀,统一跳转到移动端页面 by xu 2026-02-28
  161. const destPage = (() => {
  162. const target = String(rawDestPage || '').trim();
  163. if (!target) return '';
  164. if (target.startsWith('mp_')) return target;
  165. return `mp_${target}`;
  166. })();
  167. console.log("goToFromButton:",destPage)
  168. if (!destPage) {
  169. console.warn('按钮没有配置跳转页面:', button);
  170. return false;
  171. }
  172. const params = {
  173. ...pickPrimitiveParams(buttonConfig),
  174. ...pickPrimitiveParams(functionConfig),
  175. dest: String(rawDestPage || "").trim(),
  176. ssDest: String(rawDestPage || "").trim(),
  177. title:
  178. functionConfig.desc ||
  179. functionConfig.title ||
  180. buttonConfig.desc ||
  181. buttonConfig.title ||
  182. buttonConfig.buttonName ||
  183. buttonConfig.name ||
  184. "",
  185. service:
  186. functionConfig.servName ||
  187. buttonConfig.servName ||
  188. buttonConfig.service ||
  189. ""
  190. };
  191. mergeParamPayload(params, buttonConfig.param);
  192. mergeParamPayload(params, functionConfig.param);
  193. mergeParamPayload(params, buttonConfig.parm);
  194. mergeParamPayload(params, functionConfig.parm);
  195. const paramName = String(
  196. functionConfig.param_name || buttonConfig.param_name || ""
  197. ).trim();
  198. const paramValue =
  199. functionConfig.param_value !== undefined
  200. ? functionConfig.param_value
  201. : buttonConfig.param_value;
  202. if (
  203. paramName &&
  204. paramValue !== undefined &&
  205. paramValue !== null &&
  206. paramValue !== ""
  207. ) {
  208. params[paramName] = paramValue;
  209. }
  210. // 跳转页面,标记需要刷新
  211. this.goTo(destPage, params, { needRefresh: true });
  212. return true;
  213. },
  214. /**
  215. * 返回上一页
  216. * @param {object} options - 返回选项
  217. */
  218. goBack(options = {}) {
  219. try {
  220. // 检查是否需要刷新父页面
  221. const urlParams = new URLSearchParams(window.location.search);
  222. const needRefresh = urlParams.get('_needRefresh') === '1';
  223. const referrer = readReferrerUrl();
  224. const listTarget = normalizeLocalPageUrl(
  225. options.listPage || urlParams.get("returnTo")
  226. ) || (isListPageUrl(referrer) ? referrer : null);
  227. if (needRefresh && options.refreshParent !== false) {
  228. // 通知父页面刷新
  229. this.notifyParentRefresh();
  230. if (listTarget)
  231. this.markListRefresh(listTarget.href, options.refreshData || {});
  232. }
  233. // 返回上一页
  234. if (window.history.length > 1) {
  235. window.history.back();
  236. } else {
  237. const returnTo = listTarget;
  238. if (returnTo) {
  239. window.location.replace(returnTo.href);
  240. } else if (window.wx && window.wx.miniProgram
  241. && typeof window.wx.miniProgram.navigateBack === "function") {
  242. window.wx.miniProgram.navigateBack({ delta: 1 });
  243. }
  244. }
  245. } catch (error) {
  246. console.error('❌ 页面返回失败:', error);
  247. if (typeof showToast !== 'undefined') {
  248. showToast('页面返回失败', 'error');
  249. }
  250. }
  251. },
  252. /**
  253. * 提交成功后生成列表刷新标记。
  254. */
  255. markListRefresh(listPage, data = {}, storageValues = {}) {
  256. const target = normalizeLocalPageUrl(listPage);
  257. if (!target) return null;
  258. const payload = {
  259. listUrl: target.href,
  260. timestamp: Date.now(),
  261. data: data && typeof data === "object" ? data : {},
  262. };
  263. try {
  264. sessionStorage.setItem(LIST_RETURN_REFRESH_KEY, JSON.stringify(payload));
  265. } catch (_) {}
  266. writeSessionValues(storageValues);
  267. return payload;
  268. },
  269. /**
  270. * 列表页在 pageshow/visibilitychange 时消费刷新标记。
  271. */
  272. consumeListRefresh(currentUrl = window.location.href) {
  273. const current = normalizeLocalPageUrl(currentUrl);
  274. if (!current) return null;
  275. let record = null;
  276. try {
  277. const raw = sessionStorage.getItem(LIST_RETURN_REFRESH_KEY) || "";
  278. record = raw ? JSON.parse(raw) : null;
  279. } catch (_) {
  280. return null;
  281. }
  282. const target = normalizeLocalPageUrl(record && record.listUrl);
  283. if (!target || target.pathname !== current.pathname) return null;
  284. try {
  285. sessionStorage.removeItem(LIST_RETURN_REFRESH_KEY);
  286. } catch (_) {}
  287. return record && record.data && typeof record.data === "object"
  288. ? record.data
  289. : {};
  290. },
  291. /**
  292. * 录入页提交成功后返回列表。
  293. * 来源确为同一列表时使用 H5 历史返回;直接进入录入页时明确跳转列表。
  294. */
  295. returnToList(listPage, options = {}) {
  296. const referrer = readReferrerUrl();
  297. const target = normalizeLocalPageUrl(listPage)
  298. || (isListPageUrl(referrer) ? referrer : null);
  299. if (!target) {
  300. this.goBack({ refreshParent: true });
  301. return false;
  302. }
  303. const canUseHistory = window.history.length > 1
  304. && !!referrer
  305. && referrer.pathname === target.pathname;
  306. if (canUseHistory) {
  307. this.markListRefresh(
  308. target.href,
  309. options.refreshData || {},
  310. options.storageValues || {}
  311. );
  312. window.history.back();
  313. return true;
  314. }
  315. window.location.replace(target.href);
  316. return true;
  317. },
  318. /**
  319. * 通知父页面刷新(通过localStorage)
  320. */
  321. notifyParentRefresh() {
  322. try {
  323. const refreshData = {
  324. timestamp: Date.now(),
  325. action: 'refresh',
  326. source: window.location.pathname
  327. };
  328. localStorage.setItem('_pageRefreshNotify', JSON.stringify(refreshData));
  329. // 触发storage事件
  330. window.dispatchEvent(new StorageEvent('storage', {
  331. key: '_pageRefreshNotify',
  332. newValue: JSON.stringify(refreshData)
  333. }));
  334. console.log('📢 通知父页面刷新');
  335. } catch (error) {
  336. console.error('❌ 通知父页面刷新失败:', error);
  337. }
  338. },
  339. /**
  340. * 监听页面刷新通知
  341. * @param {function} callback - 刷新回调函数
  342. */
  343. onRefreshNotify(callback) {
  344. if (typeof callback !== 'function') {
  345. console.warn('刷新回调必须是函数');
  346. return;
  347. }
  348. // 监听localStorage变化
  349. const handleStorageChange = (event) => {
  350. if (event.key === '_pageRefreshNotify' && event.newValue) {
  351. try {
  352. const refreshData = JSON.parse(event.newValue);
  353. console.log('📢 收到页面刷新通知:', refreshData);
  354. // 执行刷新回调
  355. callback(refreshData);
  356. // 清除通知
  357. localStorage.removeItem('_pageRefreshNotify');
  358. } catch (error) {
  359. console.error('❌ 处理刷新通知失败:', error);
  360. }
  361. }
  362. };
  363. window.addEventListener('storage', handleStorageChange);
  364. // 返回清理函数
  365. return () => {
  366. window.removeEventListener('storage', handleStorageChange);
  367. };
  368. },
  369. /**
  370. * 刷新当前页面数据
  371. * @param {function} refreshCallback - 刷新数据的回调函数
  372. */
  373. refreshCurrentPage(refreshCallback) {
  374. if (typeof refreshCallback === 'function') {
  375. console.log('🔄 刷新当前页面数据');
  376. refreshCallback();
  377. } else {
  378. // 默认刷新整个页面
  379. window.location.reload();
  380. }
  381. },
  382. /**
  383. * 获取URL参数
  384. * @param {string} key - 参数名,不传则返回所有参数
  385. * @returns {string|object} 参数值或参数对象
  386. */
  387. getUrlParam(key) {
  388. const urlParams = new URLSearchParams(window.location.search);
  389. if (key) {
  390. const value = urlParams.get(key);
  391. return value ? decodeURIComponent(value) : null;
  392. }
  393. // 返回所有参数
  394. const params = {};
  395. for (const [paramKey, paramValue] of urlParams) {
  396. params[paramKey] = decodeURIComponent(paramValue);
  397. }
  398. return params;
  399. }
  400. };
  401. // 导出到全局
  402. window.NavigationManager = NavigationManager;
  403. // 兼容性:也导出为全局函数
  404. window.goTo = NavigationManager.goTo.bind(NavigationManager);
  405. window.goBack = NavigationManager.goBack.bind(NavigationManager);
  406. window.getUrlParam = NavigationManager.getUrlParam.bind(NavigationManager);
  407. window.returnToList = NavigationManager.returnToList.bind(NavigationManager);
  408. console.log('✅ H5页面导航工具加载完成');