detection.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. ;(function() {
  2. function initSentry() {
  3. try {
  4. Sentry.init({
  5. dsn: "https://ea0521e5b3584ca1879b940c165916e4@jysentry.jydev.jianyu360.cn/3",
  6. release: "v4.719",
  7. environment: "produce",
  8. sampleRate: 1,
  9. beforeSend: (event) => {
  10. let isTest = false
  11. try {
  12. isTest = window.navigator.userAgent.lastIndexOf('jy-test') !== -1
  13. } catch (e) {
  14. console.warn(e)
  15. }
  16. if (isTest) {
  17. return null
  18. }
  19. try {
  20. event.user.email = localStorage.getItem('BIGMEMBER_PC')
  21. } catch (e) {
  22. console.warn(e)
  23. }
  24. return event
  25. }
  26. });
  27. Sentry.setTag("url", location.href);
  28. var id = document.cookie.match(/(^|;)\s*ud_safe\s*=\s*([^;]+)/);
  29. Sentry.setUser({id: id && id[2]})
  30. } catch (e) {
  31. console.warn(e)
  32. }
  33. }
  34. initSentry();
  35. /**
  36. * 0. 是否需要安装、卸载SW
  37. * 1. 全局异常检测
  38. * 2. 判断是否需要激活SW刷新页面
  39. */
  40. /**
  41. * 初始化sw脚本
  42. * @param callback(params) - 回调函数
  43. * params.active - 是否注册SW成功
  44. * params.update - 是否激活并与SW通信成功
  45. * params.remove - 是否移除SW成功
  46. */
  47. function initServiceWorkerScript (callback = () => {}) {
  48. const hasServiceWorker = typeof navigator.serviceWorker !== 'undefined'
  49. if (hasServiceWorker) {
  50. const runSw = true
  51. try {
  52. navigator.serviceWorker.register('/sw.js').then((registration) => {
  53. if (runSw) {
  54. try {
  55. registration.active.postMessage({
  56. type: 'update-sw-cache'
  57. })
  58. callback({
  59. active: true,
  60. update: true
  61. })
  62. } catch (err) {
  63. console.warn(err)
  64. callback({
  65. active: true,
  66. update: false
  67. })
  68. }
  69. } else {
  70. registration.unregister().then(() => {
  71. callback({
  72. active: false,
  73. remove: true
  74. })
  75. })
  76. }
  77. }).catch((err) => {
  78. console.warn(err)
  79. callback({
  80. active: false
  81. })
  82. })
  83. } catch (err) {
  84. console.warn(err)
  85. callback({
  86. active: false
  87. })
  88. }
  89. } else {
  90. callback({
  91. active: false
  92. })
  93. }
  94. }
  95. // initServiceWorkerScript()
  96. let appendCDNDialogState = false
  97. // 插入弹窗 Node
  98. function addCDNDialogNode (content, confirm = false) {
  99. //console.log('[cdn]', 'add', content, confirm)
  100. if (!appendCDNDialogState) {
  101. const cdnStyle = document.createElement('style')
  102. cdnStyle.innerHTML = `
  103. .cdn-tip--dialog.show.action-tip .tip-button--submit {
  104. display: none;
  105. }
  106. .cdn-tip--dialog.show,
  107. .cdn-tip--dialog.show button{
  108. display: inline-block;
  109. }
  110. .cdn-tip--dialog {
  111. position: fixed;
  112. top: 20%;
  113. left: 50%;
  114. transform: translateX(-50%);
  115. display: none;
  116. box-shadow: 0 0 2px 1px #e0e0e0;
  117. border-radius: 8px;
  118. background: #FFF;
  119. padding: 32px;
  120. color: #686868;
  121. text-align: center;
  122. font-size: 14px;
  123. font-style: normal;
  124. font-weight: 400;
  125. line-height: 22px;
  126. }
  127. .cdn-tip--dialog button.tip-button--submit {
  128. background: #2ABED1;
  129. color: #FFF;
  130. }
  131. .cdn-tip--dialog button {
  132. display: none;
  133. border-radius: 6px;
  134. width: 132px;
  135. height: 36px;
  136. flex-shrink: 0;
  137. line-height: 36px;
  138. border: none;
  139. margin: 6px;
  140. cursor: pointer;
  141. }
  142. `
  143. document.head.appendChild(cdnStyle)
  144. }
  145. appendCDNDialogState = true
  146. const CDNDialogNode = document.querySelector('#cdn-tip')
  147. const hasCDNDialog = Boolean(CDNDialogNode)
  148. if (hasCDNDialog) {
  149. if (confirm) {
  150. CDNDialogNode.classList.remove('action-tip')
  151. } else {
  152. CDNDialogNode.classList.add('action-tip')
  153. }
  154. document.querySelector('#cdn-tip p').innerHTML = content
  155. return
  156. }
  157. const cdnStyle = document.createElement('style')
  158. cdnStyle.innerHTML = `
  159. <style>
  160. .cdn-tip--dialog.show.action-tip .tip-button--submit {
  161. display: none;
  162. }
  163. .cdn-tip--dialog.show,
  164. .cdn-tip--dialog.show button{
  165. display: inline-block;
  166. }
  167. .cdn-tip--dialog {
  168. min-width: 160px;
  169. position: fixed;
  170. z-index: 9999;
  171. top: 20%;
  172. left: 50%;
  173. transform: translateX(-50%);
  174. display: none;
  175. box-shadow: 0 0 2px 1px #e0e0e0;
  176. border-radius: 8px;
  177. background: #FFF;
  178. padding: 24px;
  179. color: #686868;
  180. text-align: center;
  181. font-size: 14px;
  182. font-style: normal;
  183. font-weight: 400;
  184. line-height: 22px;
  185. }
  186. .cdn-tip--dialog button.tip-button--submit {
  187. background: #2ABED1;
  188. color: #FFF;
  189. }
  190. .cdn-tip--dialog button {
  191. display: none;
  192. border-radius: 6px;
  193. width: 132px;
  194. height: 36px;
  195. flex-shrink: 0;
  196. line-height: 36px;
  197. border: none;
  198. margin: 6px;
  199. cursor: pointer;
  200. }
  201. .cdn-tip--dialog .close-tip--dialog {
  202. position: absolute;
  203. cursor: pointer;
  204. right: 0;
  205. top: 0;
  206. padding: 8px;
  207. }
  208. </style>
  209. `
  210. document.head.appendChild(cdnStyle)
  211. const cdnNode = document.createElement('div')
  212. cdnNode.innerHTML = `
  213. <div class="cdn-tip--dialog show ${confirm ? '' : 'action-tip'}" id="cdn-tip">
  214. <div class="close-tip--dialog" onclick="document.querySelector('#cdn-tip').remove();">关闭</div>
  215. <p>
  216. ${content}
  217. </p>
  218. <div>
  219. <button onclick="location.reload()" class="tip-button--submit">刷新重试</button>
  220. </div>
  221. </div>
  222. `
  223. if (document.body) {
  224. document.body.appendChild(cdnNode)
  225. }
  226. }
  227. // 异常资源数组
  228. const failedResources = []
  229. const failedResourcesMap = {}
  230. // 异常域名数组
  231. const domains = []
  232. // 备用域名映射
  233. const BackCDNs = {
  234. 'cdn-ali.jianyu360.cn': 'cdn-ali.jianyu360.com',
  235. 'cdn-ali2.jianyu360.cn': 'cdn-ali2.jianyu360.com',
  236. 'cdn-ali3.jianyu360.cn': 'cdn-ali3.jianyu360.com',
  237. 'cdn-ali4.jianyu360.cn': 'cdn-ali4.jianyu360.com',
  238. 'cdn-common.jianyu360.cn': 'cdn-common.jianyu360.com'
  239. }
  240. // 需要检测的域名索引
  241. const BackDomains = Object.keys(BackCDNs)
  242. // 处理异常资源
  243. const handleResourceError = (url, type) => {
  244. failedResources.push(url);
  245. if (!failedResourcesMap[type]) {
  246. failedResourcesMap[type] = []
  247. }
  248. failedResourcesMap[type].push(url)
  249. // 提取域名
  250. const domain = new URL(url).hostname
  251. if(!domains.includes(domain)) {
  252. domains.push(domain)
  253. }
  254. // 是否存在需要检测的域名
  255. if (BackDomains.includes(domain)) {
  256. addCDNDialogNode('加载中……')
  257. }
  258. }
  259. // 监听错误事件
  260. window.addEventListener('error', (e) => {
  261. // 脚本错误、图片错误
  262. if(e.target.src && (e.target.tagName === 'SCRIPT' || e.target.tagName === 'IMG')) {
  263. handleResourceError(e.target.src, e.target.tagName)
  264. }
  265. // CSS错误
  266. if(e.target.href && e.target.tagName === 'LINK') {
  267. handleResourceError(e.target.href, e.target.tagName)
  268. }
  269. }, true)
  270. const currentTime = Date.now()
  271. function sendError (content, options) {
  272. if (window.Sentry && typeof window.Sentry.captureMessage === 'function') {
  273. Sentry.captureMessage(content, options)
  274. }
  275. }
  276. // 异常资源随机取样
  277. function getRandomResourceByType () {
  278. let randomData = {}
  279. for (let type in failedResourcesMap) {
  280. if (failedResourcesMap.hasOwnProperty(type)) {
  281. const group = failedResourcesMap[type]
  282. // 检查 group 是否为数组
  283. if (Object.prototype.toString.call(group) === '[object Array]' && group.length > 0) {
  284. const realGroup = filterErrorURL(group)
  285. if (realGroup.length > 0) {
  286. randomData[type] = realGroup[Math.floor(Math.random() * realGroup.length)]
  287. }
  288. }
  289. }
  290. }
  291. return randomData
  292. }
  293. function filterErrorURL (urls) {
  294. return urls.filter(function (v) {
  295. return v!== location.href
  296. }).map(function (v) {
  297. let result = ''
  298. try {
  299. const uu = new URL(v)
  300. result = uu.hostname + uu.pathname
  301. } catch (e) {
  302. console.warn(e)
  303. }
  304. return result
  305. })
  306. }
  307. window.addEventListener('load', () => {
  308. // 页面完全加载完毕
  309. // console.log('load Failed resources:', failedResources)
  310. if (filterErrorURL(failedResources).length > 0) {
  311. sendError(new Error('Error Resource'), {
  312. level: 'info',
  313. tags: getRandomResourceByType(),
  314. extra: {
  315. failedResources: failedResources
  316. }
  317. })
  318. }
  319. // console.log('load Extracted domains:', domains)
  320. const hasBackCDN = Object.keys(BackCDNs).some(v => domains.includes(v))
  321. // console.log('异常域名是否包含备用', hasBackCDN)
  322. const canNext = domains.length && hasBackCDN
  323. // console.log('是否存在可修复的异常域名', canNext)
  324. if (canNext) {
  325. // 存储
  326. caches.open('CDN_INSPECT_2SW').then(cache => {
  327. cache.put('/CDN-DATA', new Response(JSON.stringify({
  328. FailedCDNs: domains,
  329. BackCDNs: BackCDNs
  330. })))
  331. })
  332. sendError(new Error('Error CDN'), {
  333. level: 'info',
  334. tags: {
  335. cdn: domains.join('、')
  336. },
  337. extra: {
  338. domains: domains,
  339. failedResources: failedResources
  340. }
  341. })
  342. addCDNDialogNode('加载中……')
  343. function stopUnlimitedReload (callback) {
  344. const saveKey = 'cdn-reload-page--' + location.href
  345. const cachePageInfo = JSON.parse(sessionStorage.getItem(saveKey) || '{}')
  346. const updateCacheAndReload = (updateTime, count, reloadTime) => {
  347. cachePageInfo.update = updateTime
  348. cachePageInfo.count = count
  349. sessionStorage.setItem(saveKey, JSON.stringify(cachePageInfo))
  350. setTimeout(() => {
  351. callback(true)
  352. }, reloadTime)
  353. }
  354. if (cachePageInfo && cachePageInfo.update) {
  355. const lastUpdateState = currentTime - cachePageInfo.update < 4000
  356. if (lastUpdateState) {
  357. if (cachePageInfo.count < 3) {
  358. cachePageInfo.count++
  359. updateCacheAndReload(currentTime, cachePageInfo.count, 1000 + (100 * cachePageInfo.count))
  360. } else {
  361. callback(false)
  362. }
  363. } else {
  364. updateCacheAndReload(currentTime, 1, 1000)
  365. }
  366. } else {
  367. updateCacheAndReload(currentTime, 1, 1000)
  368. }
  369. }
  370. initServiceWorkerScript( function (params) {
  371. //console.log('[cdn]', params, 'params')
  372. if (params.active) {
  373. sendError("[CDN] Supported")
  374. stopUnlimitedReload(function (state) {
  375. //console.log('[cdn]', 'state', state)
  376. if (state) {
  377. location.reload()
  378. } else {
  379. sendError("[CDN] Need update Supported")
  380. addCDNDialogNode('抱歉,当前故障暂无法自动修复<br>请联系剑鱼标讯客服(400-108-6670)帮您尽快解决', true)
  381. }
  382. })
  383. } else {
  384. sendError("[CDN] Not supported")
  385. addCDNDialogNode('抱歉,当前故障暂无法自动修复<br>请联系剑鱼标讯客服(400-108-6670)帮您尽快解决')
  386. }
  387. })
  388. }
  389. })
  390. })();