在套殼小程序盛行的當下, h5調用小程序能力來打破業務邊界已成爲屢見不鮮,h5與小程序的結合,極大地拓展了h5的能力邊界,豐富了h5的功能。使許多以往純h5只能想一想或者實現難度極大的功能變得輕鬆簡單。
但在套殼小程序中,h5與小程序通訊存在如下幾個問題:
因業務的特殊性,須要投放多端,小程序sdk的加載沒有放到head裏面,而是在應用啓動時動態判斷是小程序環境時自動注入的方式:web
export function injectMiniAppScript() { if (isAlipayMiniApp() || isAlipayMiniAppWebIDE()) { const s = document.createElement('script'); s.src = 'https://appx/web-view.min.js'; s.onload = () => { // 加載完成時觸發自定義事件 const customEvent = new CustomEvent('myLoad', { detail:'' }); document.dispatchEvent(customEvent); }; s.onerror = (e) => { // 加載失敗時上傳日誌 uploadLog({ tip: `INJECT_MINIAPP_SCRIPT_ERROR`, }); }; document.body.insertBefore(s, document.body.firstChild); } }
加載腳本完成後,咱們就能夠調用my.postMessage
和my.onMessage
進行通訊(統一約定h5發送消息給小程序時,必須帶action
,小程序根據action
處理業務邏輯,同時小程序處理完成的結果必須帶type
,h5在不一樣的業務場景下經過my.onMessage
處理不一樣type的響應),好比典型的,h5調用小程序簽到:
h5部分代碼以下:typescript
// 處理掃臉簽到邏輯 const faceVerify = (): Promise<AlipaySignResult> => { return new Promise((resolve) => { const handle = () => { window.my.onMessage = (result: AlipaySignResult) => { if (result.type === 'FACE_VERIFY_TIMEOUT' || result.type === 'DO_SIGN' || result.type === 'FACE_VERIFY' || result.type === 'LOCATION' || result.type === 'LOCATION_UNBELIEVABLE' || result.type === 'NOT_IN_ALIPAY') { resolve(result); } }; window.my.postMessage({ action: SIGN_CONSTANT.FACE_VERIFY, activityId: id, userId: user.userId }); }; if (window.my) { handle(); } else { // 先記錄錯誤日誌 sendErrors('/threehours.3hours-errors.NO_MY_VARIABLE', { msg: '變量不存在' }); // 監聽load事件 document.addEventListener('myLoad', handle); } }); };
實際上仍是至關繁瑣的,使用時都要先判斷my是否存在,進行不一樣的處理,一兩處還好,多了就受不了了,並且這種散亂的代碼遍及各處,甚至是不一樣的應用,因而,我封裝了下面這個sdkminiAppBus
,先來看看怎麼用,仍是上面的場景小程序
// 處理掃臉簽到邏輯 const faceVerify = (): Promise<AlipaySignResult> => { miniAppBus.postMessage({ action: SIGN_CONSTANT.FACE_VERIFY, activityId: id, userId: user.userId }); return miniAppBus.subscribeAsync<AlipaySignResult>([ 'FACE_VERIFY_TIMEOUT', 'DO_SIGN', 'FACE_VERIFY', 'LOCATION', 'LOCATION_UNBELIEVABLE', 'NOT_IN_ALIPAY', ]) };
能夠看到,不管是postMessage仍是監聽message,都不須要再關注環境,直接使用便可。在業務場景複雜的狀況下,提效尤其明顯。數組
爲了知足不一樣場景和使用的方便,公開暴露的interface以下:promise
interface MiniAppEventBus { /** * @description 回調函數訂閱單個、或多個type * @template T * @param {(string | string[])} type * @param {MiniAppMessageSubscriber<T>} callback * @memberof MiniAppEventBus */ subscribe<T extends unknown = {}>(type: string | string[], callback: MiniAppMessageSubscriber<T>): void; /** * @description Promise 訂閱單個、或多個type * @template T * @param {(string | string[])} type * @returns {Promise<MiniAppMessage<T>>} * @memberof MiniAppEventBus */ subscribeAsync<T extends {} = MiniAppMessageBase>(type: string | string[]): Promise<MiniAppMessage<T>>; /** * @description 取消訂閱單個、或多個type * @param {(string | string[])} type * @returns {Promise<void>} * @memberof MiniAppEventBus */ unSubscribe(type: string | string[]): Promise<void>; /** * @description postMessage替代,無需關注環境變量 * @param {MessageToMiniApp} msg * @returns {Promise<unknown>} * @memberof MiniAppEventBus */ postMessage(msg: MessageToMiniApp): Promise<unknown>; }
subscribe
:函數接收兩個參數,
type:須要訂閱的type,能夠是字符串,也能夠是數組。
callback:回調函數。subscribeAsync
:接收type(同上),返回Promise對象,值得注意的是,目前只要監聽到其中一個type返回,promise就resolved,將來對同一個action對應多個結果type時存在問題,須要拓展,不過目前還未遇到此類場景。unsubscribe
:取消訂閱。postMessage
:postMessage替代,無需關注環境變量。app
完整代碼:異步
import { injectMiniAppScript } from './tools'; /** * @description 小程序返回結果 * @export * @interface MiniAppMessage */ interface MiniAppMessageBase { type: string; } type MiniAppMessage<T extends unknown = {}> = MiniAppMessageBase & { [P in keyof T]: T[P] } /** * @description 小程序接收消息 * @export * @interface MessageToMiniApp */ export interface MessageToMiniApp { action: string; [x: string]: unknown } interface MiniAppMessageSubscriber<T extends unknown = {}> { (params: MiniAppMessage<T>): void } interface MiniAppEventBus { /** * @description 回調函數訂閱單個、或多個type * @template T * @param {(string | string[])} type * @param {MiniAppMessageSubscriber<T>} callback * @memberof MiniAppEventBus */ subscribe<T extends unknown = {}>(type: string | string[], callback: MiniAppMessageSubscriber<T>): void; /** * @description Promise 訂閱單個、或多個type * @template T * @param {(string | string[])} type * @returns {Promise<MiniAppMessage<T>>} * @memberof MiniAppEventBus */ subscribeAsync<T extends {} = MiniAppMessageBase>(type: string | string[]): Promise<MiniAppMessage<T>>; /** * @description 取消訂閱單個、或多個type * @param {(string | string[])} type * @returns {Promise<void>} * @memberof MiniAppEventBus */ unSubscribe(type: string | string[]): Promise<void>; /** * @description postMessage替代,無需關注環境變量 * @param {MessageToMiniApp} msg * @returns {Promise<unknown>} * @memberof MiniAppEventBus */ postMessage(msg: MessageToMiniApp): Promise<unknown>; } class MiniAppEventBus implements MiniAppEventBus{ /** * @description: 監聽函數 * @type {Map<string, MiniAppMessageSubscriber[]>} * @memberof MiniAppEventBus */ listeners: Map<string, MiniAppMessageSubscriber[]>; constructor() { this.listeners = new Map<string, Array<MiniAppMessageSubscriber<unknown>>>(); this.init(); } /** * @description 初始化 * @private * @memberof MiniAppEventBus */ private init() { if (!window.my) { // 引入腳本 injectMiniAppScript(); } this.startListen(); } /** * @description 保證my變量存在的時候執行函數func * @private * @param {Function} func * @returns * @memberof MiniAppEventBus */ private async ensureEnv(func: Function) { return new Promise((resolve) => { const promiseResolve = () => { resolve(func.call(this)); }; // 全局變量 if (window.my) { promiseResolve(); } document.addEventListener('myLoad', promiseResolve); }); } /** * @description 監聽小程序消息 * @private * @memberof MiniAppEventBus */ private listen() { window.my.onMessage = (msg: MiniAppMessage<unknown>) => { this.dispatch<unknown>(msg.type, msg); }; } private async startListen() { return this.ensureEnv(this.listen); } /** * @description 發送消息,必須包含action * @param {MessageToMiniApp} msg * @returns * @memberof MiniAppEventBus */ public postMessage(msg: MessageToMiniApp) { return new Promise((resolve) => { const realPost = () => { resolve(window.my.postMessage(msg)); }; resolve(this.ensureEnv(realPost)); }); } /** * @description 訂閱消息,支持單個或多個 * @template T * @param {(string|string[])} type * @param {MiniAppMessageSubscriber<T>} callback * @returns * @memberof MiniAppEventBus */ public subscribe<T extends unknown = {}>(type: string | string[], callback: MiniAppMessageSubscriber<T>) { const subscribeSingleAction = (type: string, cb: MiniAppMessageSubscriber<T>) => { let listeners = this.listeners.get(type) || []; listeners.push(cb); this.listeners.set(type, listeners); }; this.forEach(type,(type:string)=>subscribeSingleAction(type,callback)); } private forEach(type:string | string[],cb:(type:string)=>void){ if (typeof type === 'string') { return cb(type); } for (const key in type) { if (Object.prototype.hasOwnProperty.call(type, key)) { const element = type[key]; cb(element); } } } /** * @description 異步訂閱 * @template T * @param {(string|string[])} type * @returns {Promise<MiniAppMessage<T>>} * @memberof MiniAppEventBus */ public async subscribeAsync<T extends {} = MiniAppMessageBase>(type: string | string[]): Promise<MiniAppMessage<T>> { return new Promise((resolve, _reject) => { this.subscribe<T>(type, resolve); }); } /** * @description 觸發事件 * @param {string} type * @param {MiniAppMessage} msg * @memberof MiniAppEventBus */ public async dispatch<T = {}>(type: string, msg: MiniAppMessage<T>) { let listeners = this.listeners.get(type) || []; listeners.map(i => { if (typeof i === 'function') { i(msg); } }); } public async unSubscribe(type:string | string[]){ const unsubscribeSingle = (type: string) => { this.listeners.set(type, []); }; this.forEach(type,(type:string)=>unsubscribeSingle(type)); } } export default new MiniAppEventBus();
class內部處理了腳本加載,變量判斷,消息訂閱一系列邏輯,使用時再也不關注。async
定義action handle,經過策略模式解耦:函數
const actionHandles = { async FACE_VERIFY(){}, async GET_STEP(){}, async UPLOAD_HASH(){}, async GET_AUTH_CODE(){}, ...// 其餘action } .... // 在webview的消息監聽函數中 async startProcess(e) { const data = e.detail; // 根據不一樣的action調用不一樣的handle處理 const handle = actionHandles[data.action]; if (handle) { return actionHandles[data.action](this, data) } return uploadLogsExtend({ tip: STRING_CONTANT.UNKNOWN_ACTIONS, data }) }
使用起來也是得心順暢,舒服。post
類型完備,使用時智能提示,方便快捷。