tool.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. import * as config from '@/config/env'
  2. import store from '@/store/index'
  3. import urls from '@/server/urls'
  4. const tool = {
  5. timeSpace: 0, //本地和服务器的时间间隔
  6. fetchSKtime:0, //获取sessionkey超时的重试次数
  7. getUrlParam: function(name){
  8. const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  9. if(location.href.indexOf("?") < 0) return "";
  10. let r = location.href.split("?")[1].match(reg);
  11. if (r != null){
  12. let d = decodeURIComponent(r[2]);
  13. return tool.getIntValue(d);
  14. }
  15. return '';
  16. },
  17. getCookieValue: function(name){
  18. let nameEQ = name + "=";
  19. let ca = document.cookie.split(';');
  20. for (let i = 0; i < ca.length; i++) {
  21. let c = ca[i];
  22. while (c.charAt(0) == ' ') c = c.substring(1, c.length);
  23. if (c.indexOf(nameEQ) == 0) {
  24. return c.substring(nameEQ.length, c.length);
  25. }
  26. }
  27. return "";
  28. },
  29. getIntValue(value){
  30. if(value === 'null' || value === 'undefined' || value === null || value === undefined){
  31. return ''
  32. } else if(value === '0'){
  33. return 0
  34. }
  35. return value
  36. },
  37. createCookie(name, value, days) {
  38. let expires = "";
  39. if (days) {
  40. var date = new Date();
  41. date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  42. expires = "; expires=" + date.toGMTString();
  43. }
  44. let cookieDomain = "";
  45. if(name == "user_id" || name == "xyy"){
  46. cookieDomain = "; domain=51yund.com";
  47. }
  48. document.cookie = name + "=" + encodeURIComponent(value) + expires + cookieDomain + "; path=/";
  49. },
  50. getYdUserKey: function (key) {
  51. // 取值的时候先取store,再取storage
  52. let storeVal = store.state.comVal;
  53. let val = "";
  54. if(storeVal[key]){
  55. val = storeVal[key];
  56. } else {
  57. val = _getLocalStorage(key) || sessionStorage.getItem(key);
  58. val = tool.getIntValue(val);
  59. if(!val){
  60. val = tool.getUrlParam(key);
  61. }
  62. if(val){
  63. store.dispatch('saveCommonValue', {key:key, value: val})
  64. }
  65. }
  66. return val;
  67. },
  68. // 本地持久化存储
  69. setStorage(name, value, expires){
  70. if(window.ydStorage){
  71. ydStorage.setItem(name, value, expires)
  72. } else {
  73. localStorage.setItem(name, value);
  74. }
  75. },
  76. getSessionKey: function(userId, xyy, cb) {
  77. var param = {"user_id":userId, "xyy":xyy};
  78. return $http.post(urls.getsskey, param, true).then(function(res){
  79. if(res.code === 0){
  80. let sessionkey = res.session_key;
  81. if(sessionkey){
  82. tool.fetchSKtime = 0; //获取成功之后把fetchSKtime还原
  83. //存值的时候先存store,再存localStorage,存store为了取值更快,存storage为了看方便
  84. store.dispatch('saveCommonValue', {key:'session_key', value: sessionkey});
  85. tool.setStorage("session_key", sessionkey, res.session_ttl);
  86. store.dispatch('saveCommonValue', { 'key': 'user_id', 'value': userId });
  87. localStorage.setItem("user_id", userId);
  88. store.dispatch('saveCommonValue', { 'key': 'xyy', 'value': xyy });
  89. localStorage.setItem("xyy", xyy);
  90. }
  91. let hasLogin = userId == 0? false : true;
  92. if(cb) cb(hasLogin);
  93. return sessionkey;
  94. } else if(res.code !== 7007) { //userId和xyy不匹配或其它异常情况,最常见的场景是首次进来时,用户之前本地存储的xyy过期,7007的情况在http层统一处理
  95. tool.toLogin();
  96. }
  97. }).catch(res=>{
  98. location.href = 'https://ydcommon.51yund.com/circle_html/error_index/errIndex.html';
  99. });
  100. },
  101. //简化版js节流,默认2s内只能点击一次
  102. throttle: function(callback, duration = 2000){
  103. let lastTime = tool.lastTime || 0;
  104. let now = new Date().getTime();
  105. if(now - lastTime > duration){
  106. callback();
  107. tool.lastTime = now;
  108. }
  109. },
  110. //记录上报(访问来源上报、错误上报)
  111. reportCmd: function (data) {
  112. $http.postOnly(config.logPath + '/sport/report', data)
  113. },
  114. // 上报错误信息
  115. postErrLog(data, cmdName) {
  116. let hosts = location.host;
  117. if((hosts.indexOf("localhost") > -1 || hosts.indexOf("test") > -1) && !config.logFlag.dev){
  118. return ;
  119. }
  120. let param = {
  121. user_id: tool.getYdUserKey('user_id') || 0,
  122. cmd: cmdName,
  123. device_id: 'yuedongweb',
  124. data: JSON.stringify(data)
  125. }
  126. tool.reportCmd(param);
  127. },
  128. $throwJS(data){ //抛出js异常
  129. let obj = { //公共部分
  130. platform: "web",
  131. local_path: location.pathname,
  132. local_url: location.href,
  133. package_name: config.logFlag.packageName
  134. }
  135. Object.assign(obj, data);
  136. let filterJsErr = [];
  137. if(config.filterErr && config.filterErr.length > 0){
  138. filterJsErr.push(...config.filterErr);
  139. }
  140. if(filterJsErr.indexOf(obj.err_msg) > -1) return;
  141. let cmd_name = 'vue_jserr';
  142. if(obj.err_msg && obj.err_msg.indexOf('http') > -1){
  143. cmd_name = 'vue_reserr'; //reserr表示资源加载异常(resource error)
  144. }
  145. tool.postErrLog(obj, cmd_name);
  146. },
  147. // 抛出请求异常
  148. $throw(err, info, uri, response){
  149. let obj = {
  150. local_url: location.href,
  151. local_path: location.pathname,
  152. err_msg: err + '',
  153. req_params: info,
  154. req_uri: uri
  155. }
  156. if(response){ //返回值结构体异常
  157. obj.response = response
  158. }
  159. let filterErr = config.filterErr;
  160. if(filterErr && filterErr.indexOf(obj.err_msg) > -1) return;
  161. tool.postErrLog(obj, 'vue_reqerr');
  162. },
  163. //去登录
  164. toLogin: function(backUrl) {
  165. localStorage.removeItem('session_key');
  166. localStorage.removeItem('xyy');
  167. let cbUrl = backUrl? backUrl : location.href;
  168. cbUrl = encodeURIComponent(cbUrl);
  169. // cbUrl = _clearUlrData(cbUrl);
  170. // if(config.appId){ //如果配置了appid就走新的sso登录,否则还是走老的
  171. // location.href = `${config.ssoPath}/v${config.appVersion || 1}/user/login?appid=${config.appId}&cburl=${cbUrl}`;
  172. // } else {
  173. // location.href= config.ssoPath + "/get_tickets?cburl="+cbUrl+"&lg_way=wx"
  174. // }
  175. },
  176. }
  177. export const injectTool= () => {
  178. if (typeof window.tool == 'undefined') {
  179. window.tool = tool;
  180. }
  181. }
  182. //跳转登录时去掉url上的user_id、xyy和is_login
  183. function _clearUlrData(cbUrl) {
  184. if(cbUrl.indexOf("?") == -1) return encodeURIComponent(cbUrl);
  185. let [url, query] = cbUrl.split("?");
  186. let arr = ['user_id', 'xyy', 'is_login'];
  187. for(let i = 0; i<arr.length; i++){
  188. if(query.indexOf(arr[i]) > -1){
  189. let reg = new RegExp('(^|&)' + arr[i] +'=[^&]*', 'g');
  190. query = query.replace(reg, '')
  191. }
  192. }
  193. if(query){
  194. if(query.indexOf('&') === 0){ //最开始一位是&时去掉
  195. query = query.slice(1);
  196. }
  197. url += '?' + query
  198. }
  199. return encodeURIComponent(url)
  200. }
  201. function _getLocalStorage(name) {
  202. if(window.ydStorage){
  203. return ydStorage.getItem(name)
  204. } else {
  205. return localStorage.getItem(name);
  206. }
  207. }