native.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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: function () {
  206. NativeDataAdapter.charge = JSON.stringify(params.charge);
  207. param['charge'] = 'NativeDataAdapter.charge';
  208. var param_str = JSON.stringify(param);
  209. window.location.href = 'http://callclient?method=pay&param=' + encodeURIComponent(param_str) + '&callback=' + _callback;
  210. },
  211. wx: function () {
  212. if (config.test) {
  213. pingpp.createPayment(params.charge, function (result, err) {
  214. if (result == "success") {
  215. // 只有微信公众账号 wx_pub 支付成功的结果会在这里返回,其他的支付结果都会跳转到 extra 中对应的 URL。
  216. var res = {
  217. success: true
  218. };
  219. callback(res);
  220. } else if (result == "fail") {
  221. // charge 不正确或者微信公众账号支付失败时会在此处返回
  222. console.log(err);
  223. } else if (result == "cancel") {
  224. // 微信公众账号支付取消支付
  225. console.log(err);
  226. }
  227. });
  228. }
  229. var option = params['charge'].credential.wx_pub;
  230. var prepay = option["package"].replace('prepay_id=', '');
  231. var bookingTime = params.orderInfo.booking_time_str;
  232. var isSpecial = params['isSpecial']
  233. console.log('isSpecial1'+isSpecial);
  234. console.log(option);
  235. location.href = '/webapp/o2o/module/pay/index.html?appId='
  236. + option.appId + '&nonceStr=' + option.nonceStr
  237. + '&package=' + prepay + '&signType='
  238. + option.signType + '&timeStamp='
  239. + option.timeStamp + '&paySign='
  240. + option.paySign + '&amount=' + params['charge'].amount
  241. + '&created=' + params['charge'].created + '&body='
  242. + params['charge'].body + '&bookingTime=' + bookingTime
  243. + '&isSpecial=' + isSpecial;
  244. }
  245. });
  246. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  247. this.payCallback = callback;
  248. },
  249. //检测是否安装了微信
  250. isWxAppInstalled: function (callback) {
  251. var _callback = 'NativeCallback.isWxInstalled';
  252. var param = {};
  253. helper.osProxy({
  254. android: function () {
  255. param['callback'] = _callback;
  256. var param_str = JSON.stringify(param);
  257. window.jsapi.isWxAppInstalled(param_str);
  258. },
  259. ios: function () {
  260. var param_str = JSON.stringify(param);
  261. window.location.href = 'http://callclient?method=isWxAppInstalled&param=' + param_str + '&callback=' + _callback;
  262. }
  263. });
  264. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  265. this.isWxAppInstalledCallback = callback;
  266. },
  267. //选择地址
  268. selectAddress: function (callback) {
  269. var _callback = 'NativeCallback.selectAddress';
  270. var param = {};
  271. helper.osProxy({
  272. android: function () {
  273. param['callback'] = _callback;
  274. var param_str = JSON.stringify(param);
  275. window.jsapi.selectAddress(param_str);
  276. },
  277. ios: function () {
  278. var param_str = JSON.stringify(param);
  279. window.location.href = 'http://callclient?method=selectAddress&param=' + param_str + '&callback=' + _callback;
  280. }/*,
  281. WX: function() {
  282. require('address').getList(function(res){
  283. if (typeof(that.selectAddressCallback) == 'function') {
  284. that.selectAddressCallback(res);
  285. }
  286. })
  287. }*/
  288. });
  289. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  290. this.selectAddressCallback = callback;
  291. },
  292. //打开一个链接
  293. openURL: function (new_param) {
  294. if (config.appVersion < 2.6) {
  295. return false;
  296. }
  297. var param = {
  298. url: 'http://common.yiguanjia.me'
  299. };
  300. if (typeof new_param === 'undefined') {
  301. new_param = {};
  302. }
  303. for (var x in new_param) {
  304. if (param.hasOwnProperty(x)) {
  305. param[x] = new_param[x];
  306. }
  307. }
  308. helper.osProxy({
  309. android: function () {
  310. var param_str = JSON.stringify(param);
  311. window.jsapi.openURL(param_str);
  312. },
  313. ios: function () {
  314. var param_str = JSON.stringify(param);
  315. window.location.href = 'http://callclient?method=openURL&param=' + param_str;
  316. }
  317. });
  318. },
  319. //打开多个页面时页面之间通信
  320. postMessage: function (data) {
  321. if (config.appVersion < 2.6) {
  322. return false;
  323. }
  324. var _callback = 'NativeCallback.postMessage';
  325. helper.osProxy({
  326. android: function () {
  327. var param = {
  328. data: JSON.stringify(data),
  329. callback: _callback
  330. };
  331. var param_str = JSON.stringify(param);
  332. window.jsapi.postMessage(param_str);
  333. },
  334. ios: function () {
  335. var param = {
  336. data: data,
  337. callback: _callback
  338. };
  339. var param_str = JSON.stringify(param);
  340. window.location.href = 'http://callclient?method=postMessage&param=' + param_str;
  341. }
  342. });
  343. },
  344. //选择图片
  345. chooseImage: function (new_param, callback) {
  346. if (config.appVersion < 2.6) {
  347. return false;
  348. }
  349. var param = {
  350. sourceType: ['album', 'camera'],
  351. count: 9,
  352. clip: false,
  353. clipSize: 320
  354. };
  355. if (typeof new_param === 'undefined') {
  356. new_param = {};
  357. }
  358. for (var x in new_param) {
  359. if (param.hasOwnProperty(x)) {
  360. param[x] = new_param[x];
  361. }
  362. }
  363. var _callback = 'NativeCallback.chooseImage';
  364. helper.osProxy({
  365. android: function () {
  366. param['callback'] = _callback;
  367. var param_str = JSON.stringify(param);
  368. window.jsapi.chooseImage(param_str);
  369. },
  370. ios: function () {
  371. var param_str = JSON.stringify(param);
  372. window.location.href = 'http://callclient?method=chooseImage&param=' + param_str + '&callback=' + _callback;
  373. }
  374. });
  375. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  376. this.chooseImageCallback = callback;
  377. },
  378. //预览图片
  379. previewImage: function (urls, current) {
  380. if (!config.isWX && config.appVersion < 2.6) {
  381. return false;
  382. }
  383. var param = {
  384. urls: urls,
  385. current: current,
  386. };
  387. var param_str = JSON.stringify(param);
  388. helper.osProxy({
  389. android: function () {
  390. window.jsapi.previewImage(param_str);
  391. },
  392. ios: function () {
  393. window.location.href = 'http://callclient?method=previewImage&param=' + param_str;
  394. },
  395. wx: function () {
  396. require(['../../common/js/jweixin-1.0.0'], function (wx) {
  397. wx.previewImage({
  398. current: current, // 当前显示图片的http链接
  399. urls: urls // 需要预览的图片http链接列表
  400. });
  401. });
  402. }
  403. });
  404. },
  405. //上传图片
  406. uploadImage: function (new_param, callback) {
  407. if (config.appVersion < 2.6) {
  408. return false;
  409. }
  410. var param = {
  411. localId: '',
  412. isShowProgressTips: true,
  413. };
  414. if (typeof new_param === 'undefined') {
  415. new_param = {};
  416. }
  417. for (var x in new_param) {
  418. if (param.hasOwnProperty(x)) {
  419. param[x] = new_param[x];
  420. }
  421. }
  422. var _callback = 'NativeCallback.uploadImage';
  423. helper.osProxy({
  424. android: function () {
  425. param['callback'] = _callback;
  426. var param_str = JSON.stringify(param);
  427. window.jsapi.uploadImage(param_str);
  428. },
  429. ios: function () {
  430. var param_str = JSON.stringify(param);
  431. window.location.href = 'http://callclient?method=uploadImage&param=' + param_str + '&callback=' + _callback;
  432. }
  433. });
  434. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  435. this.uploadImageCallbacks[param.localId] = callback;
  436. },
  437. // 选择宠物
  438. selectPetType: function (callback) {
  439. var _callback = 'NativeCallback.selectPetType';
  440. var param = {};
  441. helper.osProxy({
  442. android: function () {
  443. param['callback'] = _callback;
  444. var param_str = JSON.stringify(param);
  445. window.jsapi.selectPetType(param_str);
  446. },
  447. ios: function () {
  448. var param_str = JSON.stringify(param);
  449. window.location.href = 'http://callclient?method=selectPetType&param=' + param_str + '&callback=' + _callback;
  450. }
  451. });
  452. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  453. this.selectPetTypeCallback = callback;
  454. },
  455. // 拨打电话
  456. call: function (telephone) {
  457. var that = this;
  458. helper.osProxy({
  459. android: function () {
  460. if (config.appVersion < '2.2') {
  461. //无法调用拨号,弹出
  462. $(document).trigger('spa:openpanel', ['simpleAlert', {
  463. message: '客服热线:' + telephone
  464. }]);
  465. } else {
  466. var param = {
  467. telephone: telephone
  468. };
  469. var param_str = JSON.stringify(param);
  470. window.jsapi.call(param_str);
  471. }
  472. },
  473. ios: function () {
  474. window.location.href = 'tel:' + telephone;
  475. }
  476. });
  477. },
  478. //ios
  479. //开关滑动返回
  480. switchPopGesture: function (flag) {
  481. var param = {
  482. enable: flag
  483. };
  484. helper.osProxy({
  485. ios: function () {
  486. var param_str = JSON.stringify(param);
  487. window.location.href = 'http://callclient?method=switchPopGesture&param=' + param_str;
  488. }
  489. });
  490. },
  491. //安卓
  492. //代理物理返回按钮
  493. delegateBackButton: function (flag, callback) {
  494. var param = {
  495. enable: flag,
  496. callback: 'NativeCallback.back'
  497. };
  498. helper.osProxy({
  499. android: function () {
  500. var param_str = JSON.stringify(param);
  501. window.jsapi.delegateBackButton(param_str);
  502. }
  503. });
  504. },
  505. //注册键盘事件,由于安卓回调有问题,所以改为js setInterval自定义检测
  506. registerEvent: function (enable) {
  507. if (!enable) {
  508. if (this.keyboardEventTimer != 0) {
  509. clearInterval(this.keyboardEventTimer);
  510. }
  511. return;
  512. }
  513. var that = this;
  514. this.keyboardIsOpen = false;
  515. this.keyboardIsClose = false;
  516. helper.osProxy({
  517. android: function () {
  518. that.keyboardEventTimer = setInterval(function () {
  519. if (that.originalHeight > document.body.scrollHeight) {
  520. if (!that.keyboardIsOpen) {
  521. that.keyboardIsOpen = true;
  522. that.keyboardIsClose = false;
  523. $('input, textarea').trigger('openKeyboard');
  524. }
  525. } else {
  526. if (!that.keyboardIsClose) {
  527. that.keyboardIsClose = true;
  528. that.keyboardIsOpen = false;
  529. $('input, textarea').trigger('closeKeyboard');
  530. }
  531. }
  532. }, 50);
  533. }
  534. });
  535. }
  536. };
  537. /*
  538. * 回调类
  539. */
  540. function CallbackApi() {
  541. if (typeof CallbackApi.instance === 'object') {
  542. return CallbackApi.instance;
  543. }
  544. CallbackApi.instance = this;
  545. }
  546. CallbackApi.prototype = {
  547. formatNativeParam: function (res) {
  548. var f_res = helper.osProxy({
  549. android: function () {
  550. var reg = new RegExp('(\r\n|\r|\n)', 'g');
  551. res = JSON.stringify(res).replace(reg, '');
  552. return JSON.parse(res);
  553. },
  554. ios: function () {
  555. if (res && res.hasOwnProperty('success')) {
  556. if (res.success == '1') {
  557. res.success = true;
  558. } else {
  559. res.success = false;
  560. }
  561. }
  562. return res;
  563. }
  564. });
  565. return f_res;
  566. },
  567. getUserInfo: function (res) {
  568. var f_res = this.formatNativeParam(res);
  569. var native_api = new NativeApi();
  570. if (typeof (native_api.getUserInfoCallback) == 'function') {
  571. native_api.getUserInfoCallback(f_res);
  572. }
  573. },
  574. login: function (res) {
  575. //fix by wangyang
  576. //ios客户端登陆回调的通知在2.0有点早,改为延时0.1s再重新获取一次用户信息
  577. var f_res = this.formatNativeParam(res);
  578. var nativeApi = new NativeApi();
  579. if (nativeApi.loginCallback != null) {
  580. setTimeout(function () {
  581. nativeApi.getUserInfo(nativeApi.loginCallback);
  582. nativeApi.loginCallback(f_res);
  583. }, 100);
  584. }
  585. },
  586. share: function (res) {
  587. var f_res = this.formatNativeParam(res);
  588. var native_api = new NativeApi();
  589. if (typeof (native_api.shareCallback) == 'function') {
  590. native_api.shareCallback(f_res);
  591. }
  592. },
  593. getSign: function (res) {
  594. var f_res = this.formatNativeParam(res);
  595. var native_api = new NativeApi();
  596. if (typeof (native_api.getSignCallback) == 'function') {
  597. native_api.getSignCallback(f_res);
  598. }
  599. },
  600. pay: function (res) {
  601. var f_res = this.formatNativeParam(res);
  602. if (f_res.success) {
  603. f_res.message = '支付成功';
  604. } else {
  605. helper.osProxy({
  606. android: function () {
  607. if (config.appVersion < '2.2') {
  608. if (f_res.message == 'user_cancelled') {
  609. f_res.message = '取消支付';
  610. } else {
  611. f_res.message = '支付异常,请稍后再试';
  612. }
  613. } else {
  614. switch (f_res.error_code) {
  615. case 'fail':
  616. f_res.message = '支付失败';
  617. break;
  618. case 'cancel':
  619. f_res.message = '取消支付';
  620. break;
  621. default:
  622. f_res.message = '支付异常,请稍后再试';
  623. break;
  624. }
  625. }
  626. },
  627. ios: function () {
  628. if (f_res.error_code == 5) {
  629. f_res.message = '取消支付';
  630. } else {
  631. f_res.message = '支付异常,请稍后再试';
  632. }
  633. }
  634. });
  635. }
  636. var native_api = new NativeApi();
  637. if (typeof (native_api.payCallback) == 'function') {
  638. native_api.payCallback(f_res);
  639. }
  640. },
  641. selectAddress: function (res) {
  642. var f_res = this.formatNativeParam(res);
  643. var native_api = new NativeApi();
  644. helper.osProxy({
  645. android: function () {
  646. //2.1返回的data是json字符串,特殊处理一下
  647. if (f_res.success && typeof (f_res.data) == 'string') {
  648. f_res.data = JSON.parse(f_res.data);
  649. }
  650. }
  651. });
  652. if (typeof (native_api.selectAddressCallback) == 'function') {
  653. native_api.selectAddressCallback(f_res);
  654. }
  655. },
  656. selectPetType: function (res) {
  657. var f_res = this.formatNativeParam(res);
  658. var native_api = new NativeApi();
  659. if (typeof (native_api.selectPetTypeCallback) == 'function') {
  660. native_api.selectPetTypeCallback(f_res);
  661. }
  662. },
  663. chooseImage: function (res) {
  664. var f_res = this.formatNativeParam(res);
  665. var native_api = new NativeApi();
  666. if (typeof (native_api.chooseImageCallback) == 'function') {
  667. native_api.chooseImageCallback(f_res);
  668. }
  669. },
  670. uploadImage: function (res) {
  671. var f_res = this.formatNativeParam(res);
  672. var native_api = new NativeApi();
  673. if (res.data.localId && typeof (native_api.uploadImageCallbacks[res.data.localId]) == 'function') {
  674. native_api.uploadImageCallbacks[res.data.localId](f_res);
  675. }
  676. },
  677. isWxInstalled: function (res) {
  678. var f_res = this.formatNativeParam(res);
  679. var native_api = new NativeApi();
  680. if (typeof (native_api.isWxAppInstalledCallback) == 'function') {
  681. native_api.isWxAppInstalledCallback(f_res);
  682. }
  683. },
  684. //以下回调为js自定义事件,注意,依赖jquery的trigger
  685. postMessage: function (res) {
  686. var f_res = this.formatNativeParam(res);
  687. f_res = helper.osProxy({
  688. android: function () {
  689. f_res.data = JSON.parse(f_res.data);
  690. return f_res;
  691. },
  692. ios: function () {
  693. return f_res;
  694. }
  695. });
  696. require(['$'], function ($) {
  697. $(document).trigger('postMessage', f_res);
  698. });
  699. },
  700. back: function () {
  701. require(['$'], function ($) {
  702. $(document).trigger('tapBackButton');
  703. });
  704. }
  705. };
  706. /*
  707. * 传递数据类,用于ios,某些复杂的json数据不适合通过url传递
  708. * 换一种思路,通过提供一个JS类给OC,然后OC调用js方法反查数据
  709. */
  710. function NativeDataCache() {
  711. if (typeof NativeDataCache.instance === 'object') {
  712. return NativeDataCache.instance;
  713. }
  714. NativeDataCache.instance = this;
  715. NativeDataCache.charge = '';
  716. }
  717. /**
  718. * android websocket支持
  719. */
  720. helper.osProxy({
  721. android: function () {
  722. if (typeof(WebSocketFactory) == 'undefined') {
  723. return false;
  724. }
  725. // window object
  726. var global = window;
  727. // WebSocket Object. All listener methods are cleaned up!
  728. var WebSocket = global.WebSocket = function (url) {
  729. // get a new websocket object from factory (check com.strumsoft.websocket.WebSocketFactory.java)
  730. this.socket = WebSocketFactory.getInstance(url);
  731. // store in registry
  732. if (this.socket) {
  733. WebSocket.store[this.socket.getId()] = this;
  734. } else {
  735. throw new Error('Websocket instantiation failed! Address might be wrong.');
  736. }
  737. };
  738. // private property
  739. WebSocket._keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  740. // private method for decoding base64
  741. WebSocket._decode = function (input) {
  742. var output = "";
  743. var chr1, chr2, chr3;
  744. var enc1, enc2, enc3, enc4;
  745. var i = 0;
  746. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  747. while (i < input.length) {
  748. enc1 = this._keyStr.indexOf(input.charAt(i++));
  749. enc2 = this._keyStr.indexOf(input.charAt(i++));
  750. enc3 = this._keyStr.indexOf(input.charAt(i++));
  751. enc4 = this._keyStr.indexOf(input.charAt(i++));
  752. chr1 = (enc1 << 2) | (enc2 >> 4);
  753. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  754. chr3 = ((enc3 & 3) << 6) | enc4;
  755. output = output + String.fromCharCode(chr1);
  756. if (enc3 != 64) {
  757. output = output + String.fromCharCode(chr2);
  758. }
  759. if (enc4 != 64) {
  760. output = output + String.fromCharCode(chr3);
  761. }
  762. }
  763. output = this._utf8_decode(output);
  764. return output;
  765. }
  766. // private method for UTF-8 decoding
  767. WebSocket._utf8_decode = function (utftext) {
  768. var string = "";
  769. var i = 0;
  770. var c = c1 = c2 = 0;
  771. while (i < utftext.length) {
  772. c = utftext.charCodeAt(i);
  773. if (c < 128) {
  774. string += String.fromCharCode(c);
  775. i++;
  776. } else if ((c > 191) && (c < 224)) {
  777. c2 = utftext.charCodeAt(i + 1);
  778. string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
  779. i += 2;
  780. } else {
  781. c2 = utftext.charCodeAt(i + 1);
  782. c3 = utftext.charCodeAt(i + 2);
  783. string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  784. i += 3;
  785. }
  786. }
  787. return string;
  788. }
  789. // storage to hold websocket object for later invokation of event methods
  790. WebSocket.store = {};
  791. // static event methods to call event methods on target websocket objects
  792. WebSocket.onmessage = function (evt) {
  793. WebSocket.store[evt._target]['onmessage'].call(global, this._decode(evt._data));
  794. }
  795. WebSocket.onopen = function (evt) {
  796. WebSocket.store[evt._target]['onopen'].call(global, evt);
  797. }
  798. WebSocket.onclose = function (evt) {
  799. WebSocket.store[evt._target]['onclose'].call(global, evt);
  800. }
  801. WebSocket.onerror = function (evt) {
  802. WebSocket.store[evt._target]['onerror'].call(global, evt);
  803. }
  804. // instance event methods
  805. WebSocket.prototype.send = function (data) {
  806. this.socket.send(data);
  807. }
  808. WebSocket.prototype.close = function () {
  809. this.socket.close();
  810. }
  811. WebSocket.prototype.getReadyState = function () {
  812. this.socket.getReadyState();
  813. }
  814. ///////////// Must be overloaded
  815. WebSocket.prototype.onopen = function () {
  816. throw new Error('onopen not implemented.');
  817. };
  818. // alerts message pushed from server
  819. WebSocket.prototype.onmessage = function (msg) {
  820. throw new Error('onmessage not implemented.');
  821. };
  822. // alerts message pushed from server
  823. WebSocket.prototype.onerror = function (msg) {
  824. throw new Error('onerror not implemented.');
  825. };
  826. // alert close event
  827. WebSocket.prototype.onclose = function () {
  828. throw new Error('onclose not implemented.');
  829. };
  830. }
  831. })
  832. NativeDataAdapter = new NativeDataCache();
  833. NativeCallback = new CallbackApi();
  834. return new NativeApi();
  835. })