common.js 2.52 KB
import wx from "weixin-js-sdk";

const invokeMethod = (obj) => {
    let appInterface = window.yohoInterface;
    if (appInterface) {
        appInterface.triggerEvent(obj.success || function () {
        }, obj.fail || function () {
        }, {
            method: obj.method,
            arguments: obj.args
        });
    } else {
        console.log('暂不支持,请在YOHO!BUY应用中打开');
    }
}

const linkToMiniApp = (goUrl, type) => {
    let url = goUrl || '';
    if (url && url.indexOf('http') < 0 && type === 'other') {
        url = document.location.protocol + '//' + document.location.host + url;
    }
    if (url) {
        let scene;
        if (type === 'product' || type === 'brand') {
            scene = url;
        } else {
            let base_url = decodeURIComponent(url).split('?')[0];
            let params = getQueryObj(url);
            let paramStr = '';
            Object.keys(params).forEach(key => {
                paramStr += paramStr === '' ? '?' + key + '=' + params[key] : '&' + key + '=' + params[key];
            })
            scene = '/pages/webview/webview?url=' + base_url + encodeURIComponent(paramStr);
        }
        wx.miniProgram.navigateTo({url: scene});
        return false;
    } else {
        return true;
    }
};


const getQueryObj = (link) => {
    let loc = decodeURIComponent(document.location.href);
    if (link) {
        loc = decodeURIComponent(link);
    }
    let variables = '';
    let variableArr = [];
    let finalArr = [];

    if (loc.indexOf('?') > 0) {
        variables = loc.split('?')[1];
    }

    if (variables.length > 0) {
        variableArr = variables.split('#')[0].split('&');
    }

    for (let i = 0; i < variableArr.length; i++) {
        let obj = {};

        obj.name = variableArr[i].split('=')[0];
        obj.value = variableArr[i].split('=')[1];
        finalArr.push(obj);
    }

    let query_obj = {};

    for (let i = 0; i < finalArr.length; i++) {
        query_obj[finalArr[i].name] = finalArr[i].value;
    }

    return query_obj;
};

const createLinkButton = (url, id) => {
    let a = document.createElement('a');
    a.style.position = 'fixed';
    a.style.top = 0;
    a.style.left = 0;
    a.style.border = 'none';
    a.style.outline = 'none';
    a.style.resize = 'none';
    a.style.background = 'transparent';
    a.style.color = 'transparent';
    a.setAttribute('id', id);
    a.setAttribute('href', url);
    document.body.appendChild(a);
    return a;
}
export {
    invokeMethod,
    getQueryObj,
    linkToMiniApp,
    createLinkButton
};