Files
mama-box/js/last-sub.js

40 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 11-07 用户:「在孕妈广场、笔记页或任何一个子页面,在小程序上刷新,刷新结束之后它会回到首页」。
原因:小程序刷新 / 重新进入只会加载首页地址;首页只恢复 App 表里的 H5 应用(last_app),首页自己的子页面不在表里。
做法:首页仓里的子页面(孕妈广场、笔记、我的投稿、测一测、专题页、计算器)一打开就把当前地址记在本机
localStorage「mmbox.lastsub.v1」= {u: 不带身份的路径+查询, h: 首页目录, at};页面里换笔记 / 换话题(pushState / replaceState)也跟着记。
首页被宿主重新加载时(没有 referrer、不是后退)按它回到这一页,逻辑在 app.js resumeSub()。
从别的应用后退回到子页面时,顺手清掉 last_app(同首页 clearLastAppOnBackHome),免得刷新被送回那个应用。 */
(function () {
var K = 'mmbox.lastsub.v1';
var me = document.currentScript && document.currentScript.src;
var home = me ? new URL('../', me).pathname : '';
if (!home) return;
var DROP = /^(openid|unionid|t|_v|phone|nickname|avatar|__no_identity)$/;
function save() {
try {
var q = new URLSearchParams(location.search), k = [];
q.forEach(function (v, n) { if (DROP.test(n)) k.push(n); });
k.forEach(function (n) { q.delete(n); });
var s = q.toString();
localStorage.setItem(K, JSON.stringify({ u: location.pathname + (s ? '?' + s : ''), h: home, at: Date.now() }));
} catch (e) {}
}
save();
['pushState', 'replaceState'].forEach(function (fn) {
var o = history[fn];
if (typeof o !== 'function') return;
history[fn] = function () { var r = o.apply(this, arguments); setTimeout(save, 0); return r; };
});
addEventListener('popstate', save);
addEventListener('pageshow', function (e) { if (e.persisted) save(); });
/* 从别的应用后退回来 → 清 last_app */
try {
var nav = performance.getEntriesByType && performance.getEntriesByType('navigation')[0];
var ref = document.referrer || '';
var back = (nav && nav.type === 'back_forward') || (ref.indexOf(location.origin + '/') === 0 && ref.indexOf('/mama-box') < 0);
var m = ((location.hash || '') + '&' + (location.search || '')).match(/[#?&]openid=([^&#?]*)/);
if (back && m && window.fetch) fetch('/api/mp/public/last-app?openid=' + m[1], { method: 'DELETE', keepalive: true }).catch(function () {});
} catch (e) {}
})();