native.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /**
  2. * desc: js和客户端的交互模块,尽量封装到对业务逻辑透明,为移植到其他平台做准备
  3. * author: wangyang
  4. * date: 2015-04-11
  5. */
  6. //本地回调对象
  7. var NativeCallback;
  8. var NativeDataAdapter;
  9. define(function (require) {
  10. var helper = require('helper');
  11. var config = require('config');
  12. var pingpp = require('pingpp');
  13. //客户端接口类
  14. function NativeApi() {
  15. if (typeof NativeApi.instance === 'object') {
  16. return NativeApi.instance;
  17. }
  18. NativeApi.instance = this;
  19. this.getUserInfoCallback = null;
  20. this.shareCallback = null;
  21. this.getSignCallback = null;
  22. this.loginCallback = null;
  23. this.isWxAppInstalledCallback = null;
  24. this.payCallback = null;
  25. this.selectAddressCallback = null;
  26. this.chooseImageCallback = null;
  27. this.uploadImageCallbacks = {};
  28. this.selectPetTypeCallback = null;
  29. this.charge = null;
  30. this.keyboardEventTimer = 0;
  31. this.originalHeight = document.body.scrollHeight;
  32. this.keyboardIsOpen = false;
  33. this.keyboardIsClose = false;
  34. }
  35. NativeApi.prototype = {
  36. //获取用户信息
  37. getUserInfo: function (callback) {
  38. var that = this;
  39. var _callback = 'NativeCallback.getUserInfo';
  40. helper.osProxy({
  41. android: function () {
  42. var param = {
  43. callback: _callback
  44. };
  45. var param_str = JSON.stringify(param);
  46. window.jsapi.getUserInfo(param_str);
  47. },
  48. ios: function () {
  49. window.location.href = 'http://callclient?method=getUserInfo&callback=' + _callback;
  50. },
  51. wx: function () {
  52. //此处有一个循环引用
  53. require('api').getO2oUserInfo({
  54. request_from: 'weixin',
  55. user_id: localStorage.getItem('wxUserID')
  56. }, function (res) {
  57. if (typeof(that.getUserInfoCallback) == 'function') {
  58. that.getUserInfoCallback(res);
  59. }
  60. });
  61. },
  62. cb: function () {
  63. require(['../../common/js/ctk-1.0.0'], function (ctk) {
  64. ctk.logged({
  65. yes: function (res) {
  66. console.log('已登录', res);
  67. //判断用户已登录的回调函数,用户的accessToken存放在res.accessToken内
  68. require('api').getO2oUserInfo({
  69. from: 'chubao',
  70. accessToken: res.accessToken
  71. }, function (res) {
  72. if (typeof(that.getUserInfoCallback) == 'function') {
  73. that.getUserInfoCallback(res);
  74. }
  75. });
  76. },
  77. no: function (res) {
  78. ctk.login({
  79. phone: '',
  80. success: function (res) {
  81. require('api').getO2oUserInfo({
  82. from: 'chubao',
  83. accessToken: res.accessToken
  84. }, function (res) {
  85. if (typeof(that.getUserInfoCallback) == 'function') {
  86. that.getUserInfoCallback(res);
  87. }
  88. });
  89. },
  90. fail: function (res) {
  91. // alert('login failed!');
  92. }
  93. });
  94. }
  95. });
  96. })
  97. }
  98. });
  99. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  100. this.getUserInfoCallback = callback;
  101. },
  102. //从web返回APP
  103. back: function () {
  104. helper.osProxy({
  105. android: function () {
  106. window.jsapi.exitWebView();
  107. },
  108. ios: function () {
  109. window.location.href = 'http://callclient?method=exitWebView';
  110. },
  111. wx: function () {
  112. require(['../../common/js/jweixin-1.0.0'], function (wx) {
  113. wx.closeWindow();
  114. });
  115. }
  116. });
  117. },
  118. //登录
  119. login: function (callback) {
  120. var that = this;
  121. var _callback = 'NativeCallback.login';
  122. helper.osProxy({
  123. android: function () {
  124. var param = {
  125. callback: _callback
  126. };
  127. var param_str = JSON.stringify(param);
  128. window.jsapi.goLogin(param_str);
  129. },
  130. ios: function () {
  131. window.location.href = 'http://callclient?method=goLogin&callback=' + _callback;
  132. }
  133. });
  134. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  135. this.loginCallback = callback;
  136. },
  137. //分享
  138. share: function (title, content, img_url, url, app_id, callback) {
  139. var param = {
  140. "share_title": title,
  141. "share_string": content,
  142. "share_img_url": img_url ? encodeURI(img_url) : 'http://common.yiguanjia.me/images/logo.png',
  143. "share_url": url ? encodeURI(url) : 'http://common.yiguanjia.me',
  144. "share_app_id": app_id
  145. };
  146. var _callback = 'NativeCallback.share';
  147. helper.osProxy({
  148. android: function () {
  149. param['callback'] = _callback;
  150. var param_str = JSON.stringify(param);
  151. window.jsapi.doShare(param_str);
  152. },
  153. ios: function () {
  154. var param_str = JSON.stringify(param);
  155. window.location.href = 'http://callclient?method=doShare&param=' + param_str + '&callback=' + _callback;
  156. }
  157. });
  158. var callback = typeof (arguments[5]) == 'function' ? arguments[5] : null;
  159. this.shareCallback = callback;
  160. },
  161. //参数加密验证
  162. getSign: function (param, callback) {
  163. var that = this;
  164. for (var x in param) {
  165. param[x] = param[x].toString();
  166. }
  167. var param = {
  168. sign_json_string: param
  169. };
  170. var _callback = 'NativeCallback.getSign';
  171. helper.osProxy({
  172. android: function () {
  173. param['callback'] = _callback;
  174. var param_str = JSON.stringify(param);
  175. window.jsapi.sign(param_str);
  176. },
  177. ios: function () {
  178. var param_str = JSON.stringify(param);
  179. window.location.href = 'http://callclient?method=sign&param=' + param_str + '&callback=' + _callback;
  180. },
  181. wx: function () {
  182. //目前加上参数,绕过验证,后面再加上相关的验证
  183. param['user_id'] = localStorage.getItem('wxUserID');
  184. param['request_from'] = 'weixin';
  185. if (that.getSignCallback) {
  186. that.getSignCallback(param);
  187. }
  188. }
  189. });
  190. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  191. this.getSignCallback = callback;
  192. },
  193. //支付
  194. pay: function (params, callback) {
  195. var that = this;
  196. var param = {};
  197. var _callback = 'NativeCallback.pay';
  198. helper.osProxy({
  199. android: function () {
  200. param['charge'] = params.charge;
  201. param['callback'] = _callback;
  202. var param_str = JSON.stringify(param);
  203. window.jsapi.pay(param_str);
  204. },
  205. // ios 的可以无视了,本项目暂时用不到
  206. ios: function () {
  207. NativeDataAdapter.charge = JSON.stringify(params.charge);
  208. param['charge'] = 'NativeDataAdapter.charge';
  209. var param_str = JSON.stringify(param);
  210. window.location.href = 'http://callclient?method=pay&param=' + encodeURIComponent(param_str) + '&callback=' + _callback;
  211. },
  212. wx: function () {
  213. // 这个我就不知道说什么好了,判断当前环境为test的话,走ping++模拟支付
  214. if (config.test) {
  215. pingpp.createPayment(params.charge, function (result, err) {
  216. if (result == "success") {
  217. // 只有微信公众账号 wx_pub 支付成功的结果会在这里返回,其他的支付结果都会跳转到 extra 中对应的 URL。
  218. var res = {
  219. success: true
  220. };
  221. callback(res);
  222. } else if (result == "fail") {
  223. // charge 不正确或者微信公众账号支付失败时会在此处返回
  224. console.log(err);
  225. } else if (result == "cancel") {
  226. // 微信公众账号支付取消支付
  227. console.log(err);
  228. }
  229. });
  230. }else {
  231. // 当前为正式环境,通过url传值到微信支付授权的url,然后在该url下面进行微信支付
  232. /*
  233. * 参数说明:带 * 号的为微信支付用到的
  234. * appId:* 公众号名称,由商户传入
  235. * nonceStr:* 随机串
  236. * prepay:预付款ID
  237. * signType:* 微信签名方式:
  238. * timeStamp:* 时间戳,自1970年以来的秒数
  239. * paySign:* 微信签名
  240. * amount:实付金额
  241. * created:建立
  242. * body:订单名字
  243. * bookingTime:预约时间
  244. * */
  245. var option = params['charge'].credential.wx_pub; // 支付凭据
  246. var prepay = option["package"].replace('prepay_id=', '');
  247. var bookingTime = params.orderInfo.booking_time_str;
  248. location.href = '/webapp/o2o/module/pay/index.html?appId='
  249. + option.appId + '&nonceStr=' + option.nonceStr
  250. + '&package=' + prepay + '&signType='
  251. + option.signType + '&timeStamp='
  252. + option.timeStamp + '&paySign='
  253. + option.paySign + '&amount=' + params['charge'].amount
  254. + '&created=' + params['charge'].created + '&body='
  255. + params['charge'].body + '&bookingTime=' + bookingTime;
  256. }
  257. }
  258. });
  259. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  260. this.payCallback = callback;
  261. },
  262. //检测是否安装了微信
  263. isWxAppInstalled: function (callback) {
  264. var _callback = 'NativeCallback.isWxInstalled';
  265. var param = {};
  266. helper.osProxy({
  267. android: function () {
  268. param['callback'] = _callback;
  269. var param_str = JSON.stringify(param);
  270. window.jsapi.isWxAppInstalled(param_str);
  271. },
  272. ios: function () {
  273. var param_str = JSON.stringify(param);
  274. window.location.href = 'http://callclient?method=isWxAppInstalled&param=' + param_str + '&callback=' + _callback;
  275. }
  276. });
  277. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  278. this.isWxAppInstalledCallback = callback;
  279. },
  280. //选择地址
  281. selectAddress: function (callback) {
  282. var _callback = 'NativeCallback.selectAddress';
  283. var param = {};
  284. helper.osProxy({
  285. android: function () {
  286. param['callback'] = _callback;
  287. var param_str = JSON.stringify(param);
  288. window.jsapi.selectAddress(param_str);
  289. },
  290. ios: function () {
  291. var param_str = JSON.stringify(param);
  292. window.location.href = 'http://callclient?method=selectAddress&param=' + param_str + '&callback=' + _callback;
  293. }/*,
  294. WX: function() {
  295. require('address').getList(function(res){
  296. if (typeof(that.selectAddressCallback) == 'function') {
  297. that.selectAddressCallback(res);
  298. }
  299. })
  300. }*/
  301. });
  302. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  303. this.selectAddressCallback = callback;
  304. },
  305. //打开一个链接
  306. openURL: function (new_param) {
  307. if (config.appVersion < 2.6) {
  308. return false;
  309. }
  310. var param = {
  311. url: 'http://common.yiguanjia.me'
  312. };
  313. if (typeof new_param === 'undefined') {
  314. new_param = {};
  315. }
  316. for (var x in new_param) {
  317. if (param.hasOwnProperty(x)) {
  318. param[x] = new_param[x];
  319. }
  320. }
  321. helper.osProxy({
  322. android: function () {
  323. var param_str = JSON.stringify(param);
  324. window.jsapi.openURL(param_str);
  325. },
  326. ios: function () {
  327. var param_str = JSON.stringify(param);
  328. window.location.href = 'http://callclient?method=openURL&param=' + param_str;
  329. }
  330. });
  331. },
  332. //打开多个页面时页面之间通信
  333. postMessage: function (data) {
  334. if (config.appVersion < 2.6) {
  335. return false;
  336. }
  337. var _callback = 'NativeCallback.postMessage';
  338. helper.osProxy({
  339. android: function () {
  340. var param = {
  341. data: JSON.stringify(data),
  342. callback: _callback
  343. };
  344. var param_str = JSON.stringify(param);
  345. window.jsapi.postMessage(param_str);
  346. },
  347. ios: function () {
  348. var param = {
  349. data: data,
  350. callback: _callback
  351. };
  352. var param_str = JSON.stringify(param);
  353. window.location.href = 'http://callclient?method=postMessage&param=' + param_str;
  354. }
  355. });
  356. },
  357. //选择图片
  358. chooseImage: function (new_param, callback) {
  359. if (config.appVersion < 2.6) {
  360. return false;
  361. }
  362. var param = {
  363. sourceType: ['album', 'camera'],
  364. count: 9,
  365. clip: false,
  366. clipSize: 320
  367. };
  368. if (typeof new_param === 'undefined') {
  369. new_param = {};
  370. }
  371. for (var x in new_param) {
  372. if (param.hasOwnProperty(x)) {
  373. param[x] = new_param[x];
  374. }
  375. }
  376. var _callback = 'NativeCallback.chooseImage';
  377. helper.osProxy({
  378. android: function () {
  379. param['callback'] = _callback;
  380. var param_str = JSON.stringify(param);
  381. window.jsapi.chooseImage(param_str);
  382. },
  383. ios: function () {
  384. var param_str = JSON.stringify(param);
  385. window.location.href = 'http://callclient?method=chooseImage&param=' + param_str + '&callback=' + _callback;
  386. }
  387. });
  388. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  389. this.chooseImageCallback = callback;
  390. },
  391. //预览图片
  392. previewImage: function (urls, current) {
  393. if (!config.isWX && config.appVersion < 2.6) {
  394. return false;
  395. }
  396. var param = {
  397. urls: urls,
  398. current: current,
  399. };
  400. var param_str = JSON.stringify(param);
  401. helper.osProxy({
  402. android: function () {
  403. window.jsapi.previewImage(param_str);
  404. },
  405. ios: function () {
  406. window.location.href = 'http://callclient?method=previewImage&param=' + param_str;
  407. },
  408. wx: function () {
  409. require(['../../common/js/jweixin-1.0.0'], function (wx) {
  410. wx.previewImage({
  411. current: current, // 当前显示图片的http链接
  412. urls: urls // 需要预览的图片http链接列表
  413. });
  414. });
  415. }
  416. });
  417. },
  418. //上传图片
  419. uploadImage: function (new_param, callback) {
  420. if (config.appVersion < 2.6) {
  421. return false;
  422. }
  423. var param = {
  424. localId: '',
  425. isShowProgressTips: true,
  426. };
  427. if (typeof new_param === 'undefined') {
  428. new_param = {};
  429. }
  430. for (var x in new_param) {
  431. if (param.hasOwnProperty(x)) {
  432. param[x] = new_param[x];
  433. }
  434. }
  435. var _callback = 'NativeCallback.uploadImage';
  436. helper.osProxy({
  437. android: function () {
  438. param['callback'] = _callback;
  439. var param_str = JSON.stringify(param);
  440. window.jsapi.uploadImage(param_str);
  441. },
  442. ios: function () {
  443. var param_str = JSON.stringify(param);
  444. window.location.href = 'http://callclient?method=uploadImage&param=' + param_str + '&callback=' + _callback;
  445. }
  446. });
  447. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  448. this.uploadImageCallbacks[param.localId] = callback;
  449. },
  450. // 选择宠物
  451. selectPetType: function (callback) {
  452. var _callback = 'NativeCallback.selectPetType';
  453. var param = {};
  454. helper.osProxy({
  455. android: function () {
  456. param['callback'] = _callback;
  457. var param_str = JSON.stringify(param);
  458. window.jsapi.selectPetType(param_str);
  459. },
  460. ios: function () {
  461. var param_str = JSON.stringify(param);
  462. window.location.href = 'http://callclient?method=selectPetType&param=' + param_str + '&callback=' + _callback;
  463. }
  464. });
  465. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  466. this.selectPetTypeCallback = callback;
  467. },
  468. // 拨打电话
  469. call: function (telephone) {
  470. var that = this;
  471. helper.osProxy({
  472. android: function () {
  473. if (config.appVersion < '2.2') {
  474. //无法调用拨号,弹出
  475. $(document).trigger('spa:openpanel', ['simpleAlert', {
  476. message: '客服热线:' + telephone
  477. }]);
  478. } else {
  479. var param = {
  480. telephone: telephone
  481. };
  482. var param_str = JSON.stringify(param);
  483. window.jsapi.call(param_str);
  484. }
  485. },
  486. ios: function () {
  487. window.location.href = 'tel:' + telephone;
  488. }
  489. });
  490. },
  491. //ios
  492. //开关滑动返回
  493. switchPopGesture: function (flag) {
  494. var param = {
  495. enable: flag
  496. };
  497. helper.osProxy({
  498. ios: function () {
  499. var param_str = JSON.stringify(param);
  500. window.location.href = 'http://callclient?method=switchPopGesture&param=' + param_str;
  501. }
  502. });
  503. },
  504. //安卓
  505. //代理物理返回按钮
  506. delegateBackButton: function (flag, callback) {
  507. var param = {
  508. enable: flag,
  509. callback: 'NativeCallback.back'
  510. };
  511. helper.osProxy({
  512. android: function () {
  513. var param_str = JSON.stringify(param);
  514. window.jsapi.delegateBackButton(param_str);
  515. }
  516. });
  517. },
  518. //注册键盘事件,由于安卓回调有问题,所以改为js setInterval自定义检测
  519. registerEvent: function (enable) {
  520. if (!enable) {
  521. if (this.keyboardEventTimer != 0) {
  522. clearInterval(this.keyboardEventTimer);
  523. }
  524. return;
  525. }
  526. var that = this;
  527. this.keyboardIsOpen = false;
  528. this.keyboardIsClose = false;
  529. helper.osProxy({
  530. android: function () {
  531. that.keyboardEventTimer = setInterval(function () {
  532. if (that.originalHeight > document.body.scrollHeight) {
  533. if (!that.keyboardIsOpen) {
  534. that.keyboardIsOpen = true;
  535. that.keyboardIsClose = false;
  536. $('input, textarea').trigger('openKeyboard');
  537. }
  538. } else {
  539. if (!that.keyboardIsClose) {
  540. that.keyboardIsClose = true;
  541. that.keyboardIsOpen = false;
  542. $('input, textarea').trigger('closeKeyboard');
  543. }
  544. }
  545. }, 50);
  546. }
  547. });
  548. }
  549. };
  550. /*
  551. * 回调类
  552. */
  553. function CallbackApi() {
  554. if (typeof CallbackApi.instance === 'object') {
  555. return CallbackApi.instance;
  556. }
  557. CallbackApi.instance = this;
  558. }
  559. CallbackApi.prototype = {
  560. formatNativeParam: function (res) {
  561. var f_res = helper.osProxy({
  562. android: function () {
  563. var reg = new RegExp('(\r\n|\r|\n)', 'g');
  564. res = JSON.stringify(res).replace(reg, '');
  565. return JSON.parse(res);
  566. },
  567. ios: function () {
  568. if (res && res.hasOwnProperty('success')) {
  569. if (res.success == '1') {
  570. res.success = true;
  571. } else {
  572. res.success = false;
  573. }
  574. }
  575. return res;
  576. }
  577. });
  578. return f_res;
  579. },
  580. getUserInfo: function (res) {
  581. var f_res = this.formatNativeParam(res);
  582. var native_api = new NativeApi();
  583. if (typeof (native_api.getUserInfoCallback) == 'function') {
  584. native_api.getUserInfoCallback(f_res);
  585. }
  586. },
  587. login: function (res) {
  588. //fix by wangyang
  589. //ios客户端登陆回调的通知在2.0有点早,改为延时0.1s再重新获取一次用户信息
  590. var f_res = this.formatNativeParam(res);
  591. var nativeApi = new NativeApi();
  592. if (nativeApi.loginCallback != null) {
  593. setTimeout(function () {
  594. nativeApi.getUserInfo(nativeApi.loginCallback);
  595. nativeApi.loginCallback(f_res);
  596. }, 100);
  597. }
  598. },
  599. share: function (res) {
  600. var f_res = this.formatNativeParam(res);
  601. var native_api = new NativeApi();
  602. if (typeof (native_api.shareCallback) == 'function') {
  603. native_api.shareCallback(f_res);
  604. }
  605. },
  606. getSign: function (res) {
  607. var f_res = this.formatNativeParam(res);
  608. var native_api = new NativeApi();
  609. if (typeof (native_api.getSignCallback) == 'function') {
  610. native_api.getSignCallback(f_res);
  611. }
  612. },
  613. pay: function (res) {
  614. var f_res = this.formatNativeParam(res);
  615. if (f_res.success) {
  616. f_res.message = '支付成功';
  617. } else {
  618. helper.osProxy({
  619. android: function () {
  620. if (config.appVersion < '2.2') {
  621. if (f_res.message == 'user_cancelled') {
  622. f_res.message = '取消支付';
  623. } else {
  624. f_res.message = '支付异常,请稍后再试';
  625. }
  626. } else {
  627. switch (f_res.error_code) {
  628. case 'fail':
  629. f_res.message = '支付失败';
  630. break;
  631. case 'cancel':
  632. f_res.message = '取消支付';
  633. break;
  634. default:
  635. f_res.message = '支付异常,请稍后再试';
  636. break;
  637. }
  638. }
  639. },
  640. ios: function () {
  641. if (f_res.error_code == 5) {
  642. f_res.message = '取消支付';
  643. } else {
  644. f_res.message = '支付异常,请稍后再试';
  645. }
  646. }
  647. });
  648. }
  649. var native_api = new NativeApi();
  650. if (typeof (native_api.payCallback) == 'function') {
  651. native_api.payCallback(f_res);
  652. }
  653. },
  654. selectAddress: function (res) {
  655. var f_res = this.formatNativeParam(res);
  656. var native_api = new NativeApi();
  657. helper.osProxy({
  658. android: function () {
  659. //2.1返回的data是json字符串,特殊处理一下
  660. if (f_res.success && typeof (f_res.data) == 'string') {
  661. f_res.data = JSON.parse(f_res.data);
  662. }
  663. }
  664. });
  665. if (typeof (native_api.selectAddressCallback) == 'function') {
  666. native_api.selectAddressCallback(f_res);
  667. }
  668. },
  669. selectPetType: function (res) {
  670. var f_res = this.formatNativeParam(res);
  671. var native_api = new NativeApi();
  672. if (typeof (native_api.selectPetTypeCallback) == 'function') {
  673. native_api.selectPetTypeCallback(f_res);
  674. }
  675. },
  676. chooseImage: function (res) {
  677. var f_res = this.formatNativeParam(res);
  678. var native_api = new NativeApi();
  679. if (typeof (native_api.chooseImageCallback) == 'function') {
  680. native_api.chooseImageCallback(f_res);
  681. }
  682. },
  683. uploadImage: function (res) {
  684. var f_res = this.formatNativeParam(res);
  685. var native_api = new NativeApi();
  686. if (res.data.localId && typeof (native_api.uploadImageCallbacks[res.data.localId]) == 'function') {
  687. native_api.uploadImageCallbacks[res.data.localId](f_res);
  688. }
  689. },
  690. isWxInstalled: function (res) {
  691. var f_res = this.formatNativeParam(res);
  692. var native_api = new NativeApi();
  693. if (typeof (native_api.isWxAppInstalledCallback) == 'function') {
  694. native_api.isWxAppInstalledCallback(f_res);
  695. }
  696. },
  697. //以下回调为js自定义事件,注意,依赖jquery的trigger
  698. postMessage: function (res) {
  699. var f_res = this.formatNativeParam(res);
  700. f_res = helper.osProxy({
  701. android: function () {
  702. f_res.data = JSON.parse(f_res.data);
  703. return f_res;
  704. },
  705. ios: function () {
  706. return f_res;
  707. }
  708. });
  709. require(['$'], function ($) {
  710. $(document).trigger('postMessage', f_res);
  711. });
  712. },
  713. back: function () {
  714. require(['$'], function ($) {
  715. $(document).trigger('tapBackButton');
  716. });
  717. }
  718. };
  719. /*
  720. * 传递数据类,用于ios,某些复杂的json数据不适合通过url传递
  721. * 换一种思路,通过提供一个JS类给OC,然后OC调用js方法反查数据
  722. */
  723. function NativeDataCache() {
  724. if (typeof NativeDataCache.instance === 'object') {
  725. return NativeDataCache.instance;
  726. }
  727. NativeDataCache.instance = this;
  728. NativeDataCache.charge = '';
  729. }
  730. /**
  731. * android websocket支持
  732. */
  733. helper.osProxy({
  734. android: function () {
  735. if (typeof(WebSocketFactory) == 'undefined') {
  736. return false;
  737. }
  738. // window object
  739. var global = window;
  740. // WebSocket Object. All listener methods are cleaned up!
  741. var WebSocket = global.WebSocket = function (url) {
  742. // get a new websocket object from factory (check com.strumsoft.websocket.WebSocketFactory.java)
  743. this.socket = WebSocketFactory.getInstance(url);
  744. // store in registry
  745. if (this.socket) {
  746. WebSocket.store[this.socket.getId()] = this;
  747. } else {
  748. throw new Error('Websocket instantiation failed! Address might be wrong.');
  749. }
  750. };
  751. // private property
  752. WebSocket._keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  753. // private method for decoding base64
  754. WebSocket._decode = function (input) {
  755. var output = "";
  756. var chr1, chr2, chr3;
  757. var enc1, enc2, enc3, enc4;
  758. var i = 0;
  759. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  760. while (i < input.length) {
  761. enc1 = this._keyStr.indexOf(input.charAt(i++));
  762. enc2 = this._keyStr.indexOf(input.charAt(i++));
  763. enc3 = this._keyStr.indexOf(input.charAt(i++));
  764. enc4 = this._keyStr.indexOf(input.charAt(i++));
  765. chr1 = (enc1 << 2) | (enc2 >> 4);
  766. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  767. chr3 = ((enc3 & 3) << 6) | enc4;
  768. output = output + String.fromCharCode(chr1);
  769. if (enc3 != 64) {
  770. output = output + String.fromCharCode(chr2);
  771. }
  772. if (enc4 != 64) {
  773. output = output + String.fromCharCode(chr3);
  774. }
  775. }
  776. output = this._utf8_decode(output);
  777. return output;
  778. }
  779. // private method for UTF-8 decoding
  780. WebSocket._utf8_decode = function (utftext) {
  781. var string = "";
  782. var i = 0;
  783. var c = c1 = c2 = 0;
  784. while (i < utftext.length) {
  785. c = utftext.charCodeAt(i);
  786. if (c < 128) {
  787. string += String.fromCharCode(c);
  788. i++;
  789. } else if ((c > 191) && (c < 224)) {
  790. c2 = utftext.charCodeAt(i + 1);
  791. string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
  792. i += 2;
  793. } else {
  794. c2 = utftext.charCodeAt(i + 1);
  795. c3 = utftext.charCodeAt(i + 2);
  796. string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  797. i += 3;
  798. }
  799. }
  800. return string;
  801. }
  802. // storage to hold websocket object for later invokation of event methods
  803. WebSocket.store = {};
  804. // static event methods to call event methods on target websocket objects
  805. WebSocket.onmessage = function (evt) {
  806. WebSocket.store[evt._target]['onmessage'].call(global, this._decode(evt._data));
  807. }
  808. WebSocket.onopen = function (evt) {
  809. WebSocket.store[evt._target]['onopen'].call(global, evt);
  810. }
  811. WebSocket.onclose = function (evt) {
  812. WebSocket.store[evt._target]['onclose'].call(global, evt);
  813. }
  814. WebSocket.onerror = function (evt) {
  815. WebSocket.store[evt._target]['onerror'].call(global, evt);
  816. }
  817. // instance event methods
  818. WebSocket.prototype.send = function (data) {
  819. this.socket.send(data);
  820. }
  821. WebSocket.prototype.close = function () {
  822. this.socket.close();
  823. }
  824. WebSocket.prototype.getReadyState = function () {
  825. this.socket.getReadyState();
  826. }
  827. ///////////// Must be overloaded
  828. WebSocket.prototype.onopen = function () {
  829. throw new Error('onopen not implemented.');
  830. };
  831. // alerts message pushed from server
  832. WebSocket.prototype.onmessage = function (msg) {
  833. throw new Error('onmessage not implemented.');
  834. };
  835. // alerts message pushed from server
  836. WebSocket.prototype.onerror = function (msg) {
  837. throw new Error('onerror not implemented.');
  838. };
  839. // alert close event
  840. WebSocket.prototype.onclose = function () {
  841. throw new Error('onclose not implemented.');
  842. };
  843. }
  844. })
  845. NativeDataAdapter = new NativeDataCache();
  846. NativeCallback = new CallbackApi();
  847. return new NativeApi();
  848. })