open-miniapp.js 1.32 KB
import {transToMiniappPath} from './miniapp-path-rules';

const jumpAction = ['go.productDetail', 'go.list', 'go.shop', 'go.poollist'];
let retry = 6;

function goMiniapp(apppath) {
    retry--;

    if (!window.wx) {
        if (retry > 0) {
            setTimeout(function() {
                goMiniapp(apppath);
            }, 300);
        }

        return;
    }

    let transData = transToMiniappPath(apppath);

    if (transData.path && jumpAction.indexOf(transData.action) >= 0) {
        window.wx.miniProgram.redirectTo({url: transData.path});
    }
}

function init() {
    if (window.__wxjs_environment !== 'miniprogram') {
        return;
    }

    // 添加小程序webview页面标识
    const bodyClass = 'miniapp-body';
    const $body = document.getElementsByTagName('body')[0];
    let classNames = ($body.className || '').split(' ');

    if (classNames.indexOf(bodyClass) < 0) {
        classNames.push(bodyClass);
    }

    $body.className = classNames.join(' ');

    // 自动跳转至小程序对应页面
    const appInfo = document.getElementById('main-wrap').dataset;

    if (appInfo.miniautojump && appInfo.apppath) {
        goMiniapp(appInfo.apppath);
    }
}

if (!window.WeixinJSBridge || !window.WeixinJSBridge.invoke) {
    document.addEventListener('WeixinJSBridgeReady', init, false);
} else {
    init();
}