qingjs.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. (function() {
  2. if (window.XuntongJSBridge) {
  3. // Android加上了这个if判断,如果当前window已经定义了XuntongBridge对象,不再重新加载
  4. // 避免重新初始化_callback_map等变量,导致之前的消息回调失败,返回cb404
  5. //alert('window already has a XuntongBridge object!!!');
  6. return;
  7. };
  8. /////////////////////////////////////////////////////////////////////////////////////////////////
  9. ///////////////////////////////////本地调用的实际逻辑////////////////////////////////////////////
  10. var _CUSTOM_PROTOCOL_SCHEME = 'xuntong',
  11. callbacksCount = 1,
  12. callbacks = {};
  13. function _handleMessageFromXT(callbackId, message) {
  14. try {
  15. var callback = callbacks[callbackId];
  16. if (!callback) return;
  17. callback.apply(null, [message]);
  18. } catch (e) {
  19. alert(e)
  20. }
  21. }
  22. /**
  23. * 获取用户ua信息,判断OS
  24. * @returns {string}
  25. */
  26. function getOS() {
  27. var userAgent = navigator.userAgent;
  28. return userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ? 'ios' : userAgent.match(/Android/i) ? 'android' : '';
  29. }
  30. /**
  31. * 判断用户是否在云之家桌面端中
  32. * @returns {Array|{index: number, input: string}}
  33. */
  34. function isCloudHub() {
  35. var userAgent = navigator.userAgent;
  36. return userAgent.match(/App\/cloudhub/);
  37. }
  38. // Use this in javascript to request native objective-c code
  39. // functionName : string (I think the name is explicit :p)
  40. // args : array of arguments
  41. // callback : function with n-arguments that is going to be called when the native code returned
  42. function _call(functionName, message, callback) {
  43. //只有在手机或电脑端云之家中才允许调用Xuntong JSBridge
  44. if ( !(getOS() || isCloudHub()) )return false;
  45. var hasCallback = callback && typeof callback == "function";
  46. var callbackId = hasCallback ? callbacksCount++ : 0;
  47. if (hasCallback)
  48. callbacks[callbackId] = callback;
  49. var iframe = document.createElement("IFRAME");
  50. iframe.setAttribute("src", _CUSTOM_PROTOCOL_SCHEME + ":" + functionName + ":" + callbackId + ":" + encodeURIComponent(JSON.stringify(message)));
  51. // For some reason we need to set a non-empty size for the iOS6 simulator...
  52. iframe.setAttribute("height", "1px");
  53. iframe.setAttribute("width", "1px");
  54. document.documentElement.appendChild(iframe);
  55. iframe.parentNode.removeChild(iframe);
  56. iframe = null;
  57. }
  58. var __XuntongJSBridge = {
  59. // public
  60. invoke: _call,
  61. call: _call,
  62. handleMessageFromXT: _handleMessageFromXT
  63. };
  64. window.XuntongJSBridge = __XuntongJSBridge;
  65. })();