JS问题整理与思考--Hybrid 方法封装

(function (window) {
    function _invoke(action, data, callback){
        var schema = 'myapp://utils/'+action

        schema += '?a=a'
        var key
        for(key in data){
            if (data.hasOwnProperty(key)){
                schema += '&' + key +'='+data[key]
            }
        }
        var callbackName = ''
        if (typeof callback === 'string'){
            callbackName = callback
        } else {
            callbackName = action + Date.now()
            window[callbackName] = callback
        }
        schema += 'callback='+callbackName


        var iframe = document.createElement('iframe')
        iframe.style.display = 'none'
        iframe.src = schema
        var body = document.body || document.getElementsByTagName('body')[0]
        body.appendChild(iframe)
        setTimeout(function () {
            body.removeChild(iframe)    // 销毁iframe
            iframe = null
        })

        window['weixin_scan'] = function (result) { // 创建全局函数
            alert(result)
        }
    }

    // 暴露全局变量
    window.invoke = {
        share: function (data, callback) {
            _invoke('shate',data,callback)
        },
        login: function (data, callback) {
            _invoke('login',data,callback)
        }
    }
    
})(window)

// 调用
window.invoke.share({
    title:"XXX",
    content:'asss'
},function (result) {
    alert(result)
})

随机浏览