UNPKG

jimu-bridge

Version:

a bridge-plugin for DIDI hybrid program by company FE

641 lines (614 loc) 22.9 kB
var debug = getQueryString('debug') || false; var bridgeClock; var oldbridgeClock; var browser = { versions: function () { var u = navigator.userAgent; return { //移动终端浏览器版本信息 getAppVersion: getQueryString('version') != null ? String(getQueryString('version')) : '2.2.4', isTrident: u.indexOf('Trident') > -1, //IE内核 isPresto: u.indexOf('Presto') > -1, //opera内核 isWebKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 isGecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核 isMobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 isIos: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 isAndroid: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器 isIPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器 isIPad: u.indexOf('iPad') > -1, //是否iPad isWebApp: u.indexOf('Safari') == -1 //是否web应该程序,没有头部与底部 }; }(), language: (navigator.browserLanguage || navigator.language).toLowerCase() } function getVersonNum (versionStr) { var arr = versionStr.split('.').reverse(); var value; var sum = 0; for (var i = 0; i < arr.length; i++) { value = arr[i] sum += Math.pow(100, i) * value } return sum; } function getQueryString (name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); var r = window.location.href.match(reg); if (r != null) return unescape(r[2]); return null; } const bridgeApi = { config: 'handler', debug: function (fnname, param, callback) { callback && callback({ token: window.debug.token, phone: window.debug.phone }) }, ready: function (callback) { var self = this if (window.debug && window.debug.module == true) { self.config = 'debug' callback(self) } if (window.navigator.userAgent.indexOf('didies') === -1) { //在小企业中打开 var script = document.createElement('script'); script.src = '//webapp.didistatic.com/static/webapp/shield/z/DDBridge/DDBridge/1.0.4/bridge.min.js'; document.getElementsByTagName('head')[0].appendChild(script); script.onload = function () { callback(self) } } else { //在企业版中打开 //判断是否2.4.4以上版本 // if (getVersonNum(browser.versions.getAppVersion) >= getVersonNum('2.4.4')) { // useFusion = true; // }else{ //判断是否用fusion var searchURL = window.location.search; var search = searchURL.substring(1, searchURL.length), searchlist = search.split("&"), useFusion = true; for (var i in searchlist) { if (searchlist[i] && searchlist[i].match("useFusion") && searchlist[i].match("useFusion").index > -1) { if (searchlist[i].split("=")[1] == "false") { useFusion = false; } else { useFusion = true; } } } // } if (searchURL.indexOf("useFusion") == -1) { useFusion = true; } if (useFusion) { //userFusion self.config = 'handler' self.module = window.Fusion.loadModule('CommonModule'); callback(self) } else { //oldwebview if (browser.versions.isIos) { if (window.DidiJSBridge) { try { window.DidiJSBridge.init() } catch (error) { console.log(error) } self.config = 'handlerIOS' callback(self) } else { document.addEventListener('DidiJSBridgeReady', function () { try { window.DidiJSBridge.init() } catch (error) { console.log(error) } self.config = 'handlerIOS' callback(self) }, false) } } else { oldbridgeClock = setInterval(function () { if (window.DidiJSBridge) { clearInterval(oldbridgeClock) self.config = 'handlerAndroid' callback(self) } }, 50) } } } return self; }, handlerIOS: function (fnname, param, callback) { param = param || '' window.DidiJSBridge.callHandler(fnname, param, function (res) { callback && callback.call(window, JSON.parse(res)) }) }, handlerAndroid: function (fnname, param, callback) { param = param || '' window[fnname + 'Back'] = function (res) { callback && callback.call(window, res) } window.DidiJSBridge.callHandler(fnname, param, window[fnname + 'Back']) }, //注册方法给端调用 registerHandler: function (fnname, callback) { if (this.config == 'debug') { return false } if (this.config == 'handler') { this.module[fnname] = function (res) { res = res || {} callback && callback(typeof res === 'object' ? res : JSON.parse(res)) } } else { window[fnname] = function (res) { res = res || {} callback && callback(typeof res === 'object' ? res : JSON.parse(res)) } window.DidiJSBridge.registerHandler(fnname, window[fnname]) } }, handler: function (fnname, param, callback, isAdapter) { if (!!this.module && this.module[fnname]) { var params = Array.prototype.slice.call(arguments, 1); var hybridParams if (isAdapter) { hybridParams = this.getHybridParams(params.slice(0, params.length - 1)) if (window.Fusion[fnname]) { window.Fusion[fnname].apply(this, hybridParams) } else { console.log('调用失败: 不存在' + fnname) } } else { hybridParams = this.getHybridParams(params) if (this.module[fnname]) { this.module[fnname].apply(this, hybridParams) } else { console.log('调用失败: 不存在' + fnname) } } } // if(!!this.module && this.module[fnname]){ // var fnname = arguments[0],newargu = []; // for (var x in arguments){ // if(typeof(arguments[x]) == "function"){ // //console.log(arguments[x]) // var newcallback = function(res){ // if (typeof(res) === 'string') { // arguments[x].call(window, JSON.parse(res)) // }else{ // arguments[x].call(window, res) // } // } // //console.log(newcallback) // newargu.push(arguments[x]) // //newargu.push(newcallback) // }else if(x > 0 && arguments[x] != ''){ // newargu.push(arguments[x]) // } // } // if (fnname === 'faceRecognize') { // this.adapterModule[fnname].apply(this,newargu) // } else { // this.module[fnname].apply(this,newargu) // } // } }, getHybridParams: function (paramlist) { var hybridParams = [] var item for (var i = 0; i < paramlist.length; i++) { item = paramlist[i] if (typeof (item) == "function") { var newcallback = function (res) { if (typeof (res) === 'string') { item.call(window, JSON.parse(res)) } else { item.call(window, res) } } hybridParams.push(newcallback) } else if (item != '') { hybridParams.push(item) } } return hybridParams }, setTitle: function (title) { // 设置页面标题 try { if (window.navigator.userAgent.indexOf('didies') === -1) { // 非esapp内打开 DDBridge.setTitle({ navi_title: title }); } else if (getVersonNum(browser.versions.getAppVersion) >= getVersonNum('2.2.2')) { this[this.config]('es_setTitle', JSON.stringify({ navi_title: title })); } else { this[this.config]('setTitle', JSON.stringify({ navi_title: title })); } } catch (e) { } // this[this.config]('setTitle', JSON.stringify({'navi_title': title})) document.title = title return this }, getLocationInfo: function (callback) { // 获取位置信息 console.log("getLocationInfo begin ,version ", getVersonNum(browser.versions.getAppVersion)) if (window.navigator.userAgent.indexOf('didies') === -1) { console.log("getLocationInfo bridge...") this[this.config]('getLocationInfo', '', callback) } else { if (getVersonNum(browser.versions.getAppVersion) >= getVersonNum('2.8.8')) { console.log("es_getLocationInfo bridge...") this[this.config]('es_getLocationInfo', {}, callback) } else { console.log("getLocationInfo bridge...") this[this.config]('getLocationInfo', '', callback) } } return this }, /* getLocationInfo: function (callback) { // 获取位置信息 this[this.config]('getLocationInfo', '', callback) return this }, */ getUserInfo: function (callback) { // 获取用户信息 if (getVersonNum(browser.versions.getAppVersion) >= getVersonNum('2.2.2')) { // document.getElementById('versiontest').innerHTML = browser.versions.getAppVersion + '@@ old callfunction' this[this.config]('es_getUserInfo', '', callback) } else { // document.getElementById('versiontest').innerHTML = browser.versions.getAppVersion + '@@ new callfunction' this[this.config]('getUserInfo', '', callback) } return this }, getSign: function (urlparam, callback) { // 获取data对应的签名 this[this.config]('getApiParamSignature', JSON.stringify({ data: urlparam }), callback) return this }, jumpError: function () { //华为跳转状态失败 this[this.config]('popViewController') return this }, quitWebview: function () { //退出webview 返回端 this[this.config]('popViewController') return this }, jumpSuccess: function (param) { //华为跳转状态成功 this[this.config]('pushToAuthBindViewController', JSON.stringify(param)) return this }, getAddress: function (param, callback) { //客户端选择地址 this[this.config]('pushToAddressPoiViewController', JSON.stringify(param), callback) return this }, openNewWindow: function (param) { //打开新窗口ƒ this[this.config]('openNewWindow', JSON.stringify(param)) return this }, openFellowTravelerPage: function (param) { //进入同路人的native版 this[this.config]('openFellowTravelerPage', JSON.stringify(param)) return this }, startIM: function (param) { //调起native的IM窗口 this[this.config]('startIM', JSON.stringify(param)) return this }, showConversation: function (param) { //调起或隐藏native的IM列表入口 this[this.config]('showConversation', JSON.stringify(param)) return this }, startCollectLocationData: function (param) { //开始采集坐标点 this[this.config]('startCollectLocationData', JSON.stringify({ 'phone': param })) return this }, pushNotify: function (callback) { // push通知 this.registerHandler('pushNotify', callback) return this }, enterForeground: function (callback) { //后端唤起app this.registerHandler('enterForeground', callback) return this }, rightNavButtonClicked: function (callback) { //右上角按钮的注册方法 this.registerHandler('rightNavButtonClicked', callback) return this }, playAudio: function (param) { //播放语音 this[this.config]('playAudio', JSON.stringify(param)) return this }, // bridgeApi.playAudio({"type":"1"}) share: function (param) { //分享到微信 this[this.config]('share', JSON.stringify(param)) return this }, getShowbutton: function (param) { //显示右上角的图标 取消申请和取消权限 param = param || ''; this[this.config]('showRightNavButton', JSON.stringify({ title: param })) return this }, // getApproverIds:function(callback){ //审批列表获取哪些是新的id // this[this.config]('getApproveIDS', '', callback) // return this // }, pressBackToExitWebView: function () { //后退事件 webview直接退出 this[this.config]('pressBackToExitWebView') return this }, showOrderDetail: function (param) { // 调起订单的端内页 this[this.config]('showOrderDetail', JSON.stringify(param)) return this }, // duanmeiyou getDriverAddress: function (param, callback) { // 查看司机所在位置 this[this.config]('getDriverAddressViewControl', JSON.stringify({ data: param }), callback) return this }, setH5LocalCache: function (datakey, datavalue) { // 设置缓存 this[this.config]('setH5LocalCache', JSON.stringify({ key: datakey, value: datavalue })) return this }, getH5LocalCache: function (datakey, callback) { // 获取缓存 this[this.config]('getH5LocalCache', JSON.stringify({ key: datakey }), callback) return this }, clearCache: function (callback) { // 清空缓存 this[this.config]('clearCache', '', callback) return this }, startAvatarAction: function (param, callback) { // 调起端的相机和相册 this[this.config]('startAvatarAction', JSON.stringify(param), callback) return this }, loginSuccess: function (token, company_ruler, phone) { //通知端 自动登录 this[this.config]('loginSuccess', JSON.stringify({ token: token, company_ruler: company_ruler, phone: phone })) return this }, openApprovalHistory: function (param, callback) { // 打开差旅历史列表 this[this.config]('openApprovalHistory', JSON.stringify(param), callback) return this }, openScheduleHistory: function (param, callback) { // 申请历史 this[this.config]('openScheduleHistory', JSON.stringify(param), callback) return this }, openSctxHistory: function (param, callback) { // 打开私车同行的审批历史页面 this[this.config]('openSctxHistory', JSON.stringify(param), callback) return this }, getContacts: function (param, callback) { // 获取用户通讯录 this[this.config]('getContacts', JSON.stringify(param), callback) return this }, faceRecognize: function (param, callback) { // 新版esapp走新版人脸识别(esapp 2.4.6以上使用) if (typeof param === 'function') { callback = param param = {} } console.log('trigger faceRecognize:', param, callback) this[this.config]('faceRecognize', param, callback, true) return this }, faceRecognition: function (callback) { // esapp 2.4.6以下使用 人脸识别,需要先实名认证,方可认证 this[this.config]('faceRecognition', '', callback) return this }, setTitleBarColor: function (param) { // 设置app的bar color this[this.config]('setTitleBarColor', JSON.stringify(param)) return this }, setStatusBarColor: function (param) { // 设置系统的状态栏 color this[this.config]('setStatusBarColor', JSON.stringify(param)) return this }, setComplaintStatus: function (param) { //设置端内投诉状态 this[this.config]('complaintStatus', JSON.stringify(param)) return this }, /////////////支付///////////// payByWX: function (param, callback) { //微信支付 if (this.config == 'handler') { //new view this[this.config]('payByWX', JSON.stringify(param), callback) return this } else { //oldview this[this.config]('payByWX', JSON.stringify(param)); this.registerHandler('paybackWX', callback); } }, payByAli: function (param, callback) { //支付宝支付 if (this.config == 'handler') { //new view this[this.config]('payByAli', JSON.stringify(param), callback) return this } else { //oldview this[this.config]('payByAli', JSON.stringify(param)); this.registerHandler('paybackAlipay', callback); } }, /////////////支付///////////// //返货支付页面 selectCompanyCard: function (param) { this[this.config]('selectCompanyCard', JSON.stringify(param)) return this }, //跳转端方法 openUri: function (param) { this[this.config]('openUri', JSON.stringify(param)) return this }, //打开滴滴出行APP的功能 //app_schema: OneTravel://dache/entrance 出租车 //业务线列表 http://wiki.intra.xiaojukeji.com/pages/viewpage.action?pageId=13861156 openSchema: function (app_schema, callback) { this[this.config]('openSchema', JSON.stringify({ app_schema: app_schema }), callback) return this }, //分享 //======param======= // share_url 分享的短链接 // share_content 分享文本内容 // share_title 分享标题 // share_picture 分享图片链接 // share_url_origin 分享的完整链接 // share_channel 分享渠道,以","分隔 // iconData 图片的base64 (去掉 data:image/jpg;base64,) // // =============================share_channel===================== // ONEShareSDKChannelNone = 0, // ONEShareSDKChannelWeChat = 1, // 微信好友分享 // ONEShareSDKChannelWeChatFriend = 2, // 微信朋友圈分享 // ONEShareSDKChannelAliSceneSession = 3, // 支付宝好友分享 // ONEShareSDKChannelAliSceneTimeLine = 4, // 支付宝生活圈分享 // ONEShareSDKChannelQQ = 5, // QQ好友分享 // ONEShareSDKChannelQQZone = 6, // QQ空间分享, // ONEShareSDKChannelMessage = 7, // 短信分享 // ONEShareSDKChannelWeiBo = 8, // 新浪微博分享(废弃) // ONEShareSDKChannelFacebook = 9, // Facebook 分享 // ONEShareSDKChannelFBMessenger = 10,// Facebook messenger 分享 // ONEShareSDKChannelWhatsApp = 11,// WhatsApp 分享 // ONEShareSDKChannelLine = 12,// Line 分享 // ONEShareSDKChannelTwitter = 13,// Twitter分享 // ONEShareSDKChannelEMail = 14,// e-mail 分享 commonShare: function (param) { this[this.config]('commonShare', JSON.stringify(param)) return this }, //跳转到端内登录页 jumpToEnterpriseLogin: function () { this[this.config]('dissolutionCompany') return this }, //获取apollo信息 //======param======= // apolloConfigParam key值 getApollo: function (param, callback) { this[this.config]('didiEsH5Apollo', JSON.stringify(param), callback) return this }, getDeviceInfo: function (callback) { // 获取设备信息 this[this.config]('getDeviceInfo', '', callback) return this }, copyText: function (param) { //复制 this[this.config]('copyText', JSON.stringify(param)) return this }, on_submit_callback: function (param) { //成本中心用车备注 this[this.config]('on_submit_callback', JSON.stringify(param)) return this }, getEstimatePrice: function (param, callback) { // 获取预估价返回信息 if (getVersonNum(browser.versions.getAppVersion) >= getVersonNum('2.6.0')) { this[this.config]('getEstimatePrice', JSON.stringify(param), callback); } else { this[this.config]('getEstimatePrice', '', callback); } return this }, changePayStyle: function (pay_style_name, pay_style, callback) { // 更改支付方式 this[this.config]('changePayStyle', JSON.stringify({ 'pay_style_name': pay_style_name, //支付方式的名称,如企业支付 'pay_style': pay_style //支付方式值:0代表企业支付,1代表个人支付,2代表企业+个人 }), callback) return this }, // 专车导流 carDiversion: function (param) { this[this.config]('carDiversion', JSON.stringify(param)) return this }, identifyIBMStaffInfo: function (callback) { // 认证IBM员工 this[this.config]('identifyIBMStaffInfo', '', callback) return this }, // duanmeiyou setNoReload: function (param, callback) { // 客户端返回不刷新页面设置(ios) this[this.config]('noReloadWhenViewWillAppear', JSON.stringify(param), callback) return this }, //调起 App 的登录页 callNativeLogin: function () { this[this.config]('callNativeLogin') return this }, // 页面加载完成 pageLoaded: function () { this[this.config]('pageLoaded') return this }, /** * 设置app右上角菜单 * @param {Array|string} paramArr 菜单项 "close"为关闭菜单 * -----------------menu------------------ * @param {string} title 标题 [optional (type="text"类型,需要)] * @param {string} icon 图标url [required(type="chat"类型,不用传)] * @param {Function} callback 回调函数 [required (type="chat"类型,不用传)] * @param {string} type 类型 [required] * @param {array} items 菜单项 [optinal (type="menu"时,需要)] * -----------------menu------------------ * 了解更多 @{@link http://wiki.intra.xiaojukeji.com/pages/viewpage.action?pageId=112670529} * @example * setupRightNaviBarMenu([{ title: "聊天" icon: "" callback: ()=>{} type: "chat" }, { title: "菜单", icon: "", callback: ()=>(), type: "menu", items: [{ title: "取消行程", callback: ()=>{} }, { title: "分享到", callback: ()=>{} }] }]) */ setupRightNaviBarMenu: function (paramArr) { paramArr = paramArr || [] var types = ['icon', 'chat', 'menu', 'text'] var param var self = this var checkType = function (item) { return types.includes(item.type) } var registerHandler = function (fnName, callback) { self.registerHandler(fnName, callback) } var randomName = function (fnType) { const id = '_' + Math.round(100000000 * Math.random()) const callbackName = fnType + id return callbackName } var convertCallBack = function (icon) { var fnName = randomName('rightNavBar') registerHandler(fnName, icon.callback) return Object.assign(icon, { callback: fnName }) } if (paramArr === 'close') { param = [] } else { var checkStatus = paramArr.every(checkType) if (!checkStatus) { throw new Error('Methods the parameters of rightNavArea type is only one of the [\'icon\',\'chat\', \'menu\', \'text\']') } param = paramArr.map(function (item) { var icon = convertCallBack(item) if (icon.type === 'menu') { icon.items = icon.items.map(function (menu) { return convertCallBack(menu) }) } return icon }) } this[this.config]('setupRightNaviBarMenu', JSON.stringify({ data: param })) } } window.bridgeApi = bridgeApi; module.exports = bridgeApi;