navigation.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. function pickPrimitiveParams(source = {}) {
  16. const result = {};
  17. Object.entries(source).forEach(([key, value]) => {
  18. if (NAV_IGNORED_KEYS.has(key)) return;
  19. if (value === undefined || value === null || value === "") return;
  20. const type = typeof value;
  21. if (type === "string" || type === "number" || type === "boolean") {
  22. result[key] = value;
  23. }
  24. });
  25. return result;
  26. }
  27. function normalizeParamScalar(value) {
  28. if (value === undefined || value === null) return "";
  29. const text = String(value).trim();
  30. if (!text) return "";
  31. if (
  32. (text.startsWith('"') && text.endsWith('"')) ||
  33. (text.startsWith("'") && text.endsWith("'"))
  34. ) {
  35. return text.slice(1, -1);
  36. }
  37. return text;
  38. }
  39. function mergeParamPayload(target, rawValue) {
  40. if (rawValue === undefined || rawValue === null || rawValue === "") return;
  41. if (typeof rawValue === "object" && !Array.isArray(rawValue)) {
  42. Object.entries(rawValue).forEach(([key, value]) => {
  43. if (value === undefined || value === null || value === "") return;
  44. const type = typeof value;
  45. if (type === "string" || type === "number" || type === "boolean") {
  46. target[key] = value;
  47. }
  48. });
  49. return;
  50. }
  51. if (typeof rawValue !== "string") return;
  52. const text = rawValue.trim();
  53. if (!text) return;
  54. try {
  55. const parsed = JSON.parse(text);
  56. if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
  57. mergeParamPayload(target, parsed);
  58. return;
  59. }
  60. } catch (_) {}
  61. text.split(",").forEach((segment) => {
  62. const part = String(segment || "").trim();
  63. if (!part) return;
  64. const separatorIndex = part.indexOf(":");
  65. if (separatorIndex <= 0) return;
  66. const key = normalizeParamScalar(part.slice(0, separatorIndex));
  67. const value = normalizeParamScalar(part.slice(separatorIndex + 1));
  68. if (!key || !value) return;
  69. target[key] = value;
  70. });
  71. }
  72. const NavigationManager = {
  73. /**
  74. * 跳转到目标页面
  75. * @param {string} destPage - 目标页面名称(不含.html)
  76. * @param {object} params - 传递的参数
  77. * @param {object} options - 跳转选项
  78. */
  79. goTo(destPage, params = {}, options = {}) {
  80. try {
  81. const urlParams = new URLSearchParams(window.location.search);
  82. // 添加新参数
  83. Object.keys(params).forEach(key => {
  84. if (params[key] !== undefined && params[key] !== null) {
  85. urlParams.set(key, encodeURIComponent(params[key]));
  86. }
  87. });
  88. // 添加导航标记,用于返回时刷新
  89. if (options.needRefresh) {
  90. urlParams.set('_needRefresh', '1');
  91. }
  92. // 构建目标URL
  93. const newUrl = `${destPage}.html?${urlParams.toString()}`;
  94. console.log('🔗 导航到:', newUrl);
  95. console.log('📋 传递参数:', Object.fromEntries(urlParams));
  96. // 跳转页面
  97. window.location.href = newUrl;
  98. } catch (error) {
  99. console.error('❌ 页面导航失败:', error);
  100. if (typeof showToast !== 'undefined') {
  101. showToast('页面跳转失败', 'error');
  102. } else {
  103. alert('页面跳转失败');
  104. }
  105. }
  106. },
  107. /**
  108. * 处理buttonList按钮跳转
  109. * @param {object} button - 按钮配置
  110. */
  111. goToFromButton(button) {
  112. // 优先检查function.dest,然后是button.dest
  113. const buttonConfig =
  114. button && typeof button === "object" ? button : {};
  115. const functionConfig =
  116. buttonConfig.function && typeof buttonConfig.function === "object"
  117. ? buttonConfig.function
  118. : {};
  119. const rawDestPage = functionConfig.dest || buttonConfig.dest;
  120. // 功能说明:后端返回 dest(如 objInp)时自动补齐 mp_ 前缀,统一跳转到移动端页面 by xu 2026-02-28
  121. const destPage = (() => {
  122. const target = String(rawDestPage || '').trim();
  123. if (!target) return '';
  124. if (target.startsWith('mp_')) return target;
  125. return `mp_${target}`;
  126. })();
  127. console.log("goToFromButton:",destPage)
  128. if (!destPage) {
  129. console.warn('按钮没有配置跳转页面:', button);
  130. return false;
  131. }
  132. const params = {
  133. ...pickPrimitiveParams(buttonConfig),
  134. ...pickPrimitiveParams(functionConfig),
  135. dest: String(rawDestPage || "").trim(),
  136. ssDest: String(rawDestPage || "").trim(),
  137. title:
  138. functionConfig.desc ||
  139. functionConfig.title ||
  140. buttonConfig.desc ||
  141. buttonConfig.title ||
  142. buttonConfig.buttonName ||
  143. buttonConfig.name ||
  144. "",
  145. service:
  146. functionConfig.servName ||
  147. buttonConfig.servName ||
  148. buttonConfig.service ||
  149. ""
  150. };
  151. mergeParamPayload(params, buttonConfig.param);
  152. mergeParamPayload(params, functionConfig.param);
  153. mergeParamPayload(params, buttonConfig.parm);
  154. mergeParamPayload(params, functionConfig.parm);
  155. const paramName = String(
  156. functionConfig.param_name || buttonConfig.param_name || ""
  157. ).trim();
  158. const paramValue =
  159. functionConfig.param_value !== undefined
  160. ? functionConfig.param_value
  161. : buttonConfig.param_value;
  162. if (
  163. paramName &&
  164. paramValue !== undefined &&
  165. paramValue !== null &&
  166. paramValue !== ""
  167. ) {
  168. params[paramName] = paramValue;
  169. }
  170. // 跳转页面,标记需要刷新
  171. this.goTo(destPage, params, { needRefresh: true });
  172. return true;
  173. },
  174. /**
  175. * 返回上一页
  176. * @param {object} options - 返回选项
  177. */
  178. goBack(options = {}) {
  179. try {
  180. // 检查是否需要刷新父页面
  181. const urlParams = new URLSearchParams(window.location.search);
  182. const needRefresh = urlParams.get('_needRefresh') === '1';
  183. if (needRefresh && options.refreshParent !== false) {
  184. // 通知父页面刷新
  185. this.notifyParentRefresh();
  186. }
  187. // 返回上一页
  188. if (window.history.length > 1) {
  189. window.history.back();
  190. } else {
  191. NavigationManager.goBack()
  192. }
  193. } catch (error) {
  194. console.error('❌ 页面返回失败:', error);
  195. if (typeof showToast !== 'undefined') {
  196. showToast('页面返回失败', 'error');
  197. }
  198. }
  199. },
  200. /**
  201. * 通知父页面刷新(通过localStorage)
  202. */
  203. notifyParentRefresh() {
  204. try {
  205. const refreshData = {
  206. timestamp: Date.now(),
  207. action: 'refresh',
  208. source: window.location.pathname
  209. };
  210. localStorage.setItem('_pageRefreshNotify', JSON.stringify(refreshData));
  211. // 触发storage事件
  212. window.dispatchEvent(new StorageEvent('storage', {
  213. key: '_pageRefreshNotify',
  214. newValue: JSON.stringify(refreshData)
  215. }));
  216. console.log('📢 通知父页面刷新');
  217. } catch (error) {
  218. console.error('❌ 通知父页面刷新失败:', error);
  219. }
  220. },
  221. /**
  222. * 监听页面刷新通知
  223. * @param {function} callback - 刷新回调函数
  224. */
  225. onRefreshNotify(callback) {
  226. if (typeof callback !== 'function') {
  227. console.warn('刷新回调必须是函数');
  228. return;
  229. }
  230. // 监听localStorage变化
  231. const handleStorageChange = (event) => {
  232. if (event.key === '_pageRefreshNotify' && event.newValue) {
  233. try {
  234. const refreshData = JSON.parse(event.newValue);
  235. console.log('📢 收到页面刷新通知:', refreshData);
  236. // 执行刷新回调
  237. callback(refreshData);
  238. // 清除通知
  239. localStorage.removeItem('_pageRefreshNotify');
  240. } catch (error) {
  241. console.error('❌ 处理刷新通知失败:', error);
  242. }
  243. }
  244. };
  245. window.addEventListener('storage', handleStorageChange);
  246. // 返回清理函数
  247. return () => {
  248. window.removeEventListener('storage', handleStorageChange);
  249. };
  250. },
  251. /**
  252. * 刷新当前页面数据
  253. * @param {function} refreshCallback - 刷新数据的回调函数
  254. */
  255. refreshCurrentPage(refreshCallback) {
  256. if (typeof refreshCallback === 'function') {
  257. console.log('🔄 刷新当前页面数据');
  258. refreshCallback();
  259. } else {
  260. // 默认刷新整个页面
  261. window.location.reload();
  262. }
  263. },
  264. /**
  265. * 获取URL参数
  266. * @param {string} key - 参数名,不传则返回所有参数
  267. * @returns {string|object} 参数值或参数对象
  268. */
  269. getUrlParam(key) {
  270. const urlParams = new URLSearchParams(window.location.search);
  271. if (key) {
  272. const value = urlParams.get(key);
  273. return value ? decodeURIComponent(value) : null;
  274. }
  275. // 返回所有参数
  276. const params = {};
  277. for (const [paramKey, paramValue] of urlParams) {
  278. params[paramKey] = decodeURIComponent(paramValue);
  279. }
  280. return params;
  281. }
  282. };
  283. // 导出到全局
  284. window.NavigationManager = NavigationManager;
  285. // 兼容性:也导出为全局函数
  286. window.goTo = NavigationManager.goTo.bind(NavigationManager);
  287. window.goBack = NavigationManager.goBack.bind(NavigationManager);
  288. window.getUrlParam = NavigationManager.getUrlParam.bind(NavigationManager);
  289. console.log('✅ H5页面导航工具加载完成');