前端知识hybird

Web调用APP方法

2018-02-12  本文已影响41人  yimi珊

封装useApp.js

useApp.js

//ios
function setupWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
function connectWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) {
        callback(WebViewJavascriptBridge)
    } else {
        document.addEventListener(
            'WebViewJavascriptBridgeReady'
            , function() {
                callback(WebViewJavascriptBridge)
            },
            false
        );
    }
}
var u = navigator.userAgent;
window.isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
window.isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
window.client = {};
window.client.init = function( callback ){
    if(isAndroid){
        connectWebViewJavascriptBridge(function (bridge) {
            bridge.init(function(message, responseCallback) {
                console.log('JS got a message', message);
                var data = {
                    'Javascript Responds': '测试中文!'
                };
                console.log('JS responding with', data); 
                responseCallback(data);
            });
            // generateClient(bridge);  
            callback && callback(bridge);      
        });
    }else if(isiOS){
        setupWebViewJavascriptBridge(function (bridge) {
            // generateClient(bridge);        
            callback && callback(bridge);                  
        });
    }
}
window.client.init(function(bridge){
    window.appExec = bridge;
    // 获取 token
    bridge.callHandler('getUserToken', null , function(tokenIn) {
        window.client.token = tokenIn;
        //alert(window.client.token)
        //cb && cb();
    })
    // 退出
})

在js中引入useApp.js文件

import useapp from 'useapp.js地址';

调用方法

appExec.callHandler('方法名', '参数',function(返回数据){
  //对返回数据进行处理
});
上一篇下一篇

猜你喜欢

热点阅读