Files
mama-box/js/share-card.js

55 lines
2.8 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-04 用户:「孕期百问 / 计算器 / 趣味小测 / 孕妈广场所有能转发的内容都做 5:4 转发图,带兜爸心选 logo,核心内容大字」)
图是预先生成的静态 jpg(750×600),放在 assets/share/:
t/<专题 slug>.jpg 百问专题 / 计算器(topic/*)
c/<测试 id>.jpg 趣味小测(guangchang/ceshi/?id=)
g/<笔记 id>.jpg 广场笔记(?n=);g/t-<话题 id>.jpg 话题(?t=);g/home.jpg 广场;g/ceshi.jpg 测试列表
生成脚本在 tools/share-card/(node build.js 出清单 → python3 render.py 截图;icons.json 由 index.html CS_TI / app.js QA_IC 导出),改了标题 / 新增内容要重跑。
协议:wx.miniProgram.postMessage({action:'location', href, title, imageUrl}),宿主 shareCard 用它覆盖转发卡(box_app/docs/h5-auth-standard.md 第四节)。
postMessage 不是实时投递,微信在分享那一刻才派发,所以每次换内容都要再报一次;子页面没引 jweixin,这里按需加载。 */
(function (g) {
'use strict';
var V = '26110440';
var isWx = /MicroMessenger/i.test(navigator.userAgent || '');
var waiting = [], loading = false;
function ready(cb) {
if (g.wx && g.wx.miniProgram && g.wx.miniProgram.postMessage) { cb(); return; }
if (!isWx) return; /* 普通浏览器不用报 */
waiting.push(cb);
if (loading) return;
loading = true;
var s = document.createElement('script');
s.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
s.onload = function () { var l = waiting; waiting = []; l.forEach(function (f) { try { f(); } catch (e) {} }); };
document.head.appendChild(s);
}
/* img:相对当前页的图片路径;title:转发卡标题(缺省用页面标题) */
function share(img, title) {
var abs = '';
try { if (img) abs = new URL(img, document.baseURI).href.split('#')[0] + '?v=' + V; } catch (e) {}
var t = title || document.title || '';
ready(function () {
try { g.wx.miniProgram.postMessage({ data: { action: 'location', href: location.href, title: t, imageUrl: abs } }); } catch (e) {}
});
}
/* 单页里内容随地址变(pushState / replaceState / popstate / hashchange):get() 返回 [img, title],同一地址只报一次 */
function watch(get) {
var last = '';
function pull() {
var k = location.pathname + location.search;
if (k === last) return;
last = k;
var r = get() || [];
share(r[0], r[1]);
}
['pushState', 'replaceState'].forEach(function (fn) {
var o = history[fn];
history[fn] = function () { var r = o.apply(this, arguments); setTimeout(pull, 0); return r; };
});
g.addEventListener('popstate', pull);
g.addEventListener('hashchange', pull);
pull();
}
g.mbShare = share;
g.mbShareWatch = watch;
})(window);