native.js 34 KB

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