native.js 34 KB

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