vue-debug-helper

Vue components debug helper

2022-05-09 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. // ==UserScript==
  2. // @name vue-debug-helper
  3. // @name:en vue-debug-helper
  4. // @name:zh Vue调试分析助手
  5. // @name:zh-TW Vue調試分析助手
  6. // @name:ja Vueデバッグ分析アシスタント
  7. // @namespace https://github.com/xxxily/vue-debug-helper
  8. // @homepage https://github.com/xxxily/vue-debug-helper
  9. // @version 0.0.10
  10. // @description Vue components debug helper
  11. // @description:en Vue components debug helper
  12. // @description:zh Vue组件探测、统计、分析辅助脚本
  13. // @description:zh-TW Vue組件探測、統計、分析輔助腳本
  14. // @description:ja Vueコンポーネントの検出、統計、分析補助スクリプト
  15. // @author ankvps
  16. // @icon https://cdn.jsdelivr.net/gh/xxxily/vue-debug-helper@main/logo.png
  17. // @match http://*/*
  18. // @match https://*/*
  19. // @grant unsafeWindow
  20. // @grant GM_addStyle
  21. // @grant GM_setValue
  22. // @grant GM_getValue
  23. // @grant GM_deleteValue
  24. // @grant GM_listValues
  25. // @grant GM_addValueChangeListener
  26. // @grant GM_removeValueChangeListener
  27. // @grant GM_registerMenuCommand
  28. // @grant GM_unregisterMenuCommand
  29. // @grant GM_getTab
  30. // @grant GM_saveTab
  31. // @grant GM_getTabs
  32. // @grant GM_openInTab
  33. // @grant GM_download
  34. // @grant GM_xmlhttpRequest
  35. // @run-at document-start
  36. // @connect 127.0.0.1
  37. // @license GPL
  38. // ==/UserScript==
  39. (function (w) { if (w) { w._vueDebugHelper_ = 'https://github.com/xxxily/vue-debug-helper'; } })();
  40.  
  41. class AssertionError extends Error {}
  42. AssertionError.prototype.name = 'AssertionError';
  43.  
  44. /**
  45. * Minimal assert function
  46. * @param {any} t Value to check if falsy
  47. * @param {string=} m Optional assertion error message
  48. * @throws {AssertionError}
  49. */
  50. function assert (t, m) {
  51. if (!t) {
  52. var err = new AssertionError(m);
  53. if (Error.captureStackTrace) Error.captureStackTrace(err, assert);
  54. throw err
  55. }
  56. }
  57.  
  58. /* eslint-env browser */
  59.  
  60. let ls;
  61. if (typeof window === 'undefined' || typeof window.localStorage === 'undefined') {
  62. // A simple localStorage interface so that lsp works in SSR contexts. Not for persistant storage in node.
  63. const _nodeStorage = {};
  64. ls = {
  65. getItem (name) {
  66. return _nodeStorage[name] || null
  67. },
  68. setItem (name, value) {
  69. if (arguments.length < 2) throw new Error('Failed to execute \'setItem\' on \'Storage\': 2 arguments required, but only 1 present.')
  70. _nodeStorage[name] = (value).toString();
  71. },
  72. removeItem (name) {
  73. delete _nodeStorage[name];
  74. }
  75. };
  76. } else {
  77. ls = window.localStorage;
  78. }
  79.  
  80. var localStorageProxy = (name, opts = {}) => {
  81. assert(name, 'namepace required');
  82. const {
  83. defaults = {},
  84. lspReset = false,
  85. storageEventListener = true
  86. } = opts;
  87.  
  88. const state = new EventTarget();
  89. try {
  90. const restoredState = JSON.parse(ls.getItem(name)) || {};
  91. if (restoredState.lspReset !== lspReset) {
  92. ls.removeItem(name);
  93. for (const [k, v] of Object.entries({
  94. ...defaults
  95. })) {
  96. state[k] = v;
  97. }
  98. } else {
  99. for (const [k, v] of Object.entries({
  100. ...defaults,
  101. ...restoredState
  102. })) {
  103. state[k] = v;
  104. }
  105. }
  106. } catch (e) {
  107. console.error(e);
  108. ls.removeItem(name);
  109. }
  110.  
  111. state.lspReset = lspReset;
  112.  
  113. if (storageEventListener && typeof window !== 'undefined' && typeof window.addEventListener !== 'undefined') {
  114. state.addEventListener('storage', (ev) => {
  115. // Replace state with whats stored on localStorage... it is newer.
  116. for (const k of Object.keys(state)) {
  117. delete state[k];
  118. }
  119. const restoredState = JSON.parse(ls.getItem(name)) || {};
  120. for (const [k, v] of Object.entries({
  121. ...defaults,
  122. ...restoredState
  123. })) {
  124. state[k] = v;
  125. }
  126. opts.lspReset = restoredState.lspReset;
  127. state.dispatchEvent(new Event('update'));
  128. });
  129. }
  130.  
  131. function boundHandler (rootRef) {
  132. return {
  133. get (obj, prop) {
  134. if (typeof obj[prop] === 'object' && obj[prop] !== null) {
  135. return new Proxy(obj[prop], boundHandler(rootRef))
  136. } else if (typeof obj[prop] === 'function' && obj === rootRef && prop !== 'constructor') {
  137. // this returns bound EventTarget functions
  138. return obj[prop].bind(obj)
  139. } else {
  140. return obj[prop]
  141. }
  142. },
  143. set (obj, prop, value) {
  144. obj[prop] = value;
  145. try {
  146. ls.setItem(name, JSON.stringify(rootRef));
  147. rootRef.dispatchEvent(new Event('update'));
  148. return true
  149. } catch (e) {
  150. console.error(e);
  151. return false
  152. }
  153. }
  154. }
  155. }
  156.  
  157. return new Proxy(state, boundHandler(state))
  158. };
  159.  
  160. /**
  161. * 对特定数据结构的对象进行排序
  162. * @param {object} obj 一个对象,其结构应该类似于:{key1: [], key2: []}
  163. * @param {boolean} reverse -可选 是否反转、降序排列,默认为false
  164. * @param {object} opts -可选 指定数组的配置项,默认为{key: 'key', value: 'value'}
  165. * @param {object} opts.key -可选 指定对象键名的别名,默认为'key'
  166. * @param {object} opts.value -可选 指定对象值的别名,默认为'value'
  167. * @returns {array} 返回一个数组,其结构应该类似于:[{key: key1, value: []}, {key: key2, value: []}]
  168. */
  169. const objSort = (obj, reverse, opts = { key: 'key', value: 'value' }) => {
  170. const arr = [];
  171. for (const key in obj) {
  172. if (Object.prototype.hasOwnProperty.call(obj, key) && Array.isArray(obj[key])) {
  173. const tmpObj = {};
  174. tmpObj[opts.key] = key;
  175. tmpObj[opts.value] = obj[key];
  176. arr.push(tmpObj);
  177. }
  178. }
  179.  
  180. arr.sort((a, b) => {
  181. return a[opts.value].length - b[opts.value].length
  182. });
  183.  
  184. reverse && arr.reverse();
  185. return arr
  186. };
  187.  
  188. /**
  189. * 根据指定长度创建空白数据
  190. * @param {number} size -可选 指str的重复次数,默认为1024次,如果str为单个单字节字符,则意味着默认产生1Mb的空白数据
  191. * @param {string|number|any} str - 可选 指定数据的字符串,默认为'd'
  192. */
  193. function createEmptyData (count = 1024, str = 'd') {
  194. const arr = [];
  195. arr.length = count + 1;
  196. return arr.join(str)
  197. }
  198.  
  199. /**
  200. * 将字符串分隔的过滤器转换为数组形式的过滤器
  201. * @param {string|array} filter - 必选 字符串或数组,字符串支持使用 , |符号对多个项进行分隔
  202. * @returns {array}
  203. */
  204. function toArrFilters (filter) {
  205. filter = filter || [];
  206.  
  207. /* 如果是字符串,则支持通过, | 两个符号来指定多个组件名称的过滤器 */
  208. if (typeof filter === 'string') {
  209. /* 移除前后的, |分隔符,防止出现空字符的过滤规则 */
  210. filter.replace(/^(,|\|)/, '').replace(/(,|\|)$/, '');
  211.  
  212. if (/\|/.test(filter)) {
  213. filter = filter.split('|');
  214. } else {
  215. filter = filter.split(',');
  216. }
  217. }
  218.  
  219. filter = filter.map(item => item.trim());
  220.  
  221. return filter
  222. }
  223.  
  224. /**
  225. * 判断某个字符串是否跟filters相匹配
  226. * @param {array|string} filters - 必选 字符串或数组,字符串支持使用 , |符号对多个项进行分隔
  227. * @param {string|number} str - 必选 一个字符串或数字,用于跟过滤器进行匹配判断
  228. */
  229. function filtersMatch (filters, str) {
  230. if (!filters || !str) {
  231. return false
  232. }
  233.  
  234. filters = Array.isArray(filters) ? filters : toArrFilters(filters);
  235. str = String(str);
  236.  
  237. let result = false;
  238. for (let i = 0; i < filters.length; i++) {
  239. let filter = String(filters[i]);
  240.  
  241. /* 带星表示进行模糊匹配,且不区分大小写 */
  242. if (/\*/.test(filter)) {
  243. filter = filter.replace(/\*/g, '').toLocaleLowerCase();
  244. if (str.toLocaleLowerCase().indexOf(filter) > -1) {
  245. result = true;
  246. break
  247. }
  248. } else if (filter.includes(str)) {
  249. result = true;
  250. break
  251. }
  252. }
  253.  
  254. return result
  255. }
  256.  
  257. const inBrowser = typeof window !== 'undefined';
  258.  
  259. function getVueDevtools () {
  260. return inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__
  261. }
  262.  
  263. class Debug {
  264. constructor (msg, printTime = false) {
  265. const t = this;
  266. msg = msg || 'debug message:';
  267. t.log = t.createDebugMethod('log', null, msg);
  268. t.error = t.createDebugMethod('error', null, msg);
  269. t.info = t.createDebugMethod('info', null, msg);
  270. t.warn = t.createDebugMethod('warn', null, msg);
  271. }
  272.  
  273. create (msg) {
  274. return new Debug(msg)
  275. }
  276.  
  277. createDebugMethod (name, color, tipsMsg) {
  278. name = name || 'info';
  279.  
  280. const bgColorMap = {
  281. info: '#2274A5',
  282. log: '#95B46A',
  283. warn: '#F5A623',
  284. error: '#D33F49'
  285. };
  286.  
  287. const printTime = this.printTime;
  288.  
  289. return function () {
  290. if (!window._debugMode_) {
  291. return false
  292. }
  293.  
  294. const msg = tipsMsg || 'debug message:';
  295.  
  296. const arg = Array.from(arguments);
  297. arg.unshift(`color: white; background-color: ${color || bgColorMap[name] || '#95B46A'}`);
  298.  
  299. if (printTime) {
  300. const curTime = new Date();
  301. const H = curTime.getHours();
  302. const M = curTime.getMinutes();
  303. const S = curTime.getSeconds();
  304. arg.unshift(`%c [${H}:${M}:${S}] ${msg} `);
  305. } else {
  306. arg.unshift(`%c ${msg} `);
  307. }
  308.  
  309. window.console[name].apply(window.console, arg);
  310. }
  311. }
  312.  
  313. isDebugMode () {
  314. return Boolean(window._debugMode_)
  315. }
  316. }
  317.  
  318. var Debug$1 = new Debug();
  319.  
  320. var debug = Debug$1.create('vueDebugHelper:');
  321.  
  322. /**
  323. * 简单的i18n库
  324. */
  325.  
  326. class I18n {
  327. constructor (config) {
  328. this._languages = {};
  329. this._locale = this.getClientLang();
  330. this._defaultLanguage = '';
  331. this.init(config);
  332. }
  333.  
  334. init (config) {
  335. if (!config) return false
  336.  
  337. const t = this;
  338. t._locale = config.locale || t._locale;
  339. /* 指定当前要是使用的语言环境,默认无需指定,会自动读取 */
  340. t._languages = config.languages || t._languages;
  341. t._defaultLanguage = config.defaultLanguage || t._defaultLanguage;
  342. }
  343.  
  344. use () {}
  345.  
  346. t (path) {
  347. const t = this;
  348. let result = t.getValByPath(t._languages[t._locale] || {}, path);
  349.  
  350. /* 版本回退 */
  351. if (!result && t._locale !== t._defaultLanguage) {
  352. result = t.getValByPath(t._languages[t._defaultLanguage] || {}, path);
  353. }
  354.  
  355. return result || ''
  356. }
  357.  
  358. /* 当前语言值 */
  359. language () {
  360. return this._locale
  361. }
  362.  
  363. languages () {
  364. return this._languages
  365. }
  366.  
  367. changeLanguage (locale) {
  368. if (this._languages[locale]) {
  369. this._languages = locale;
  370. return locale
  371. } else {
  372. return false
  373. }
  374. }
  375.  
  376. /**
  377. * 根据文本路径获取对象里面的值
  378. * @param obj {Object} -必选 要操作的对象
  379. * @param path {String} -必选 路径信息
  380. * @returns {*}
  381. */
  382. getValByPath (obj, path) {
  383. path = path || '';
  384. const pathArr = path.split('.');
  385. let result = obj;
  386.  
  387. /* 递归提取结果值 */
  388. for (let i = 0; i < pathArr.length; i++) {
  389. if (!result) break
  390. result = result[pathArr[i]];
  391. }
  392.  
  393. return result
  394. }
  395.  
  396. /* 获取客户端当前的语言环境 */
  397. getClientLang () {
  398. return navigator.languages ? navigator.languages[0] : navigator.language
  399. }
  400. }
  401.  
  402. var zhCN = {
  403. about: '关于',
  404. issues: '反馈',
  405. setting: '设置',
  406. hotkeys: '快捷键',
  407. donate: '赞赏',
  408. debugHelper: {
  409. viewVueDebugHelperObject: 'vueDebugHelper对象',
  410. componentsStatistics: '当前存活组件统计',
  411. destroyStatisticsSort: '已销毁组件统计',
  412. componentsSummaryStatisticsSort: '全部组件混合统计',
  413. getDestroyByDuration: '组件存活时间信息',
  414. clearAll: '清空统计信息',
  415. printLifeCycleInfo: '打印组件生命周期信息',
  416. notPrintLifeCycleInfo: '取消组件生命周期信息打印',
  417. printLifeCycleInfoPrompt: {
  418. lifecycleFilters: '输入要打印的生命周期名称,多个可用,或|分隔,不输入则默认打印created',
  419. componentFilters: '输入要打印的组件名称,多个可用,或|分隔,不输入则默认打印所有组件'
  420. },
  421. findComponents: '查找组件',
  422. findComponentsPrompt: {
  423. filters: '输入要查找的组件名称,或uid,多个可用,或|分隔'
  424. },
  425. findNotContainElementComponents: '查找不包含DOM对象的组件',
  426. blockComponents: '阻断组件的创建',
  427. blockComponentsPrompt: {
  428. filters: '输入要阻断的组件名称,多个可用,或|分隔,输入为空则取消阻断'
  429. },
  430. dd: '数据注入(dd)',
  431. undd: '取消数据注入(undd)',
  432. ddPrompt: {
  433. filter: '组件过滤器(如果为空,则对所有组件注入)',
  434. count: '指定注入数据的重复次数(默认1024)'
  435. },
  436. toggleHackVueComponent: '改写/还原Vue.component',
  437. hackVueComponent: {
  438. hack: '改写Vue.component',
  439. unhack: '还原Vue.component'
  440. },
  441. devtools: {
  442. enabled: '自动开启vue-devtools',
  443. disable: '禁止开启vue-devtools'
  444. }
  445. }
  446. };
  447.  
  448. var enUS = {
  449. about: 'about',
  450. issues: 'feedback',
  451. setting: 'settings',
  452. hotkeys: 'Shortcut keys',
  453. donate: 'donate',
  454. debugHelper: {
  455. viewVueDebugHelperObject: 'vueDebugHelper object',
  456. componentsStatistics: 'Current surviving component statistics',
  457. destroyStatisticsSort: 'Destroyed component statistics',
  458. componentsSummaryStatisticsSort: 'All components mixed statistics',
  459. getDestroyByDuration: 'Component survival time information',
  460. clearAll: 'Clear statistics',
  461. dd: 'Data injection (dd)',
  462. undd: 'Cancel data injection (undd)',
  463. ddPrompt: {
  464. filter: 'Component filter (if empty, inject all components)',
  465. count: 'Specify the number of repetitions of injected data (default 1024)'
  466. }
  467. }
  468. };
  469.  
  470. var zhTW = {
  471. about: '關於',
  472. issues: '反饋',
  473. setting: '設置',
  474. hotkeys: '快捷鍵',
  475. donate: '讚賞',
  476. debugHelper: {
  477. viewVueDebugHelperObject: 'vueDebugHelper對象',
  478. componentsStatistics: '當前存活組件統計',
  479. destroyStatisticsSort: '已銷毀組件統計',
  480. componentsSummaryStatisticsSort: '全部組件混合統計',
  481. getDestroyByDuration: '組件存活時間信息',
  482. clearAll: '清空統計信息',
  483. dd: '數據注入(dd)',
  484. undd: '取消數據注入(undd)',
  485. ddPrompt: {
  486. filter: '組件過濾器(如果為空,則對所有組件注入)',
  487. count: '指定注入數據的重複次數(默認1024)'
  488. }
  489. }
  490. };
  491.  
  492. const messages = {
  493. 'zh-CN': zhCN,
  494. zh: zhCN,
  495. 'zh-HK': zhTW,
  496. 'zh-TW': zhTW,
  497. 'en-US': enUS,
  498. en: enUS,
  499. };
  500.  
  501. /*!
  502. * @name i18n.js
  503. * @description vue-debug-helper的国际化配置
  504. * @version 0.0.1
  505. * @author xxxily
  506. * @date 2022/04/26 14:56
  507. * @github https://github.com/xxxily
  508. */
  509.  
  510. const i18n = new I18n({
  511. defaultLanguage: 'en',
  512. /* 指定当前要是使用的语言环境,默认无需指定,会自动读取 */
  513. // locale: 'zh-TW',
  514. languages: messages
  515. });
  516.  
  517. window.vueDebugHelper = {
  518. /* 存储全部未被销毁的组件对象 */
  519. components: {},
  520. /* 存储全部创建过的组件的概要信息,即使销毁了概要信息依然存在 */
  521. componentsSummary: {},
  522. /* 基于componentsSummary的组件情况统计 */
  523. componentsSummaryStatistics: {},
  524. /* 已销毁的组件概要信息列表 */
  525. destroyList: [],
  526. /* 基于destroyList的组件情况统计 */
  527. destroyStatistics: {},
  528.  
  529. config: {
  530. /* 是否在控制台打印组件生命周期的相关信息 */
  531. lifecycle: {
  532. show: false,
  533. filters: ['created'],
  534. componentFilters: []
  535. },
  536.  
  537. /* 查找组件的过滤器配置 */
  538. findComponentsFilters: [],
  539.  
  540. /* 阻止组件创建的过滤器 */
  541. blockFilters: [],
  542.  
  543. devtools: true,
  544.  
  545. /* 改写Vue.component */
  546. hackVueComponent: false,
  547.  
  548. /* 给组件注入空白数据的配置信息 */
  549. dd: {
  550. enabled: false,
  551. filters: [],
  552. count: 1024
  553. }
  554. }
  555. };
  556.  
  557. const helper = window.vueDebugHelper;
  558.  
  559. /* 配置信息跟localStorage联动 */
  560. const state = localStorageProxy('vueDebugHelperConfig', {
  561. defaults: helper.config,
  562. lspReset: false,
  563. storageEventListener: false
  564. });
  565. helper.config = state;
  566.  
  567. const methods = {
  568. objSort,
  569. createEmptyData,
  570. /* 清除全部helper的全部记录数据,以便重新统计 */
  571. clearAll () {
  572. helper.components = {};
  573. helper.componentsSummary = {};
  574. helper.componentsSummaryStatistics = {};
  575. helper.destroyList = [];
  576. helper.destroyStatistics = {};
  577. },
  578.  
  579. /**
  580. * 对当前的helper.components进行统计与排序
  581. * 如果一直没运行过清理函数,则表示统计页面创建至今依然存活的组件对象
  582. * 运行过清理函数,则表示统计清理后新创建且至今依然存活的组件对象
  583. */
  584. componentsStatistics (reverse = true) {
  585. const tmpObj = {};
  586.  
  587. Object.keys(helper.components).forEach(key => {
  588. const component = helper.components[key];
  589.  
  590. tmpObj[component._componentName]
  591. ? tmpObj[component._componentName].push(component)
  592. : (tmpObj[component._componentName] = [component]);
  593. });
  594.  
  595. return objSort(tmpObj, reverse, {
  596. key: 'componentName',
  597. value: 'componentInstance'
  598. })
  599. },
  600.  
  601. /**
  602. * 对componentsSummaryStatistics进行排序输出,以便可以直观查看组件的创建情况
  603. */
  604. componentsSummaryStatisticsSort (reverse = true) {
  605. return objSort(helper.componentsSummaryStatistics, reverse, {
  606. key: 'componentName',
  607. value: 'componentsSummary'
  608. })
  609. },
  610.  
  611. /**
  612. * 对destroyList进行排序输出,以便可以直观查看组件的销毁情况
  613. */
  614. destroyStatisticsSort (reverse = true) {
  615. return objSort(helper.destroyStatistics, reverse, {
  616. key: 'componentName',
  617. value: 'destroyList'
  618. })
  619. },
  620.  
  621. /**
  622. * 对destroyList进行排序输出,以便可以直观查看组件的销毁情况
  623. */
  624. getDestroyByDuration (duration = 1000) {
  625. const destroyList = helper.destroyList;
  626. const destroyListLength = destroyList.length;
  627. const destroyListDuration = destroyList.map(item => item.duration).sort();
  628. const maxDuration = Math.max(...destroyListDuration);
  629. const minDuration = Math.min(...destroyListDuration);
  630. const avgDuration = destroyListDuration.reduce((a, b) => a + b, 0) / destroyListLength;
  631. const durationRange = maxDuration - minDuration;
  632. const durationRangePercent = (duration - minDuration) / durationRange;
  633.  
  634. return {
  635. destroyList,
  636. destroyListLength,
  637. destroyListDuration,
  638. maxDuration,
  639. minDuration,
  640. avgDuration,
  641. durationRange,
  642. durationRangePercent
  643. }
  644. },
  645.  
  646. /**
  647. * 获取组件的调用链信息
  648. */
  649. getComponentChain (component, moreDetail = false) {
  650. const result = [];
  651. let current = component;
  652. let deep = 0;
  653.  
  654. while (current && deep < 50) {
  655. deep++;
  656.  
  657. /**
  658. * 由于脚本注入的运行时间会比应用创建时间晚,所以会导致部分先创建的组件缺少相关信息
  659. * 这里尝试对部分信息进行修复,以便更好的查看组件的创建情况
  660. */
  661. if (!current._componentTag) {
  662. const tag = current.$vnode?.tag || current.$options?._componentTag || current._uid;
  663. current._componentTag = tag;
  664. current._componentName = isNaN(Number(tag)) ? tag.replace(/^vue-component-\d+-/, '') : 'anonymous-component';
  665. }
  666.  
  667. if (moreDetail) {
  668. result.push({
  669. tag: current._componentTag,
  670. name: current._componentName,
  671. componentsSummary: helper.componentsSummary[current._uid] || null
  672. });
  673. } else {
  674. result.push(current._componentName);
  675. }
  676.  
  677. current = current.$parent;
  678. }
  679.  
  680. if (moreDetail) {
  681. return result
  682. } else {
  683. return result.join(' -> ')
  684. }
  685. },
  686.  
  687. printLifeCycleInfo (lifecycleFilters, componentFilters) {
  688. lifecycleFilters = toArrFilters(lifecycleFilters);
  689. componentFilters = toArrFilters(componentFilters);
  690.  
  691. helper.config.lifecycle = {
  692. show: true,
  693. filters: lifecycleFilters,
  694. componentFilters: componentFilters
  695. };
  696. },
  697. notPrintLifeCycleInfo () {
  698. helper.config.lifecycle.show = false;
  699. },
  700.  
  701. /**
  702. * 查找组件
  703. * @param {string|array} filters 组件名称或组件uid的过滤器,可以是字符串或者数组,如果是字符串多个过滤选可用,或|分隔
  704. * 如果过滤项是数字,则跟组件的id进行精确匹配,如果是字符串,则跟组件的tag信息进行模糊匹配
  705. * @returns {object} {components: [], componentNames: []}
  706. */
  707. findComponents (filters) {
  708. filters = toArrFilters(filters);
  709.  
  710. /* 对filters进行预处理,如果为纯数字则表示通过id查找组件 */
  711. filters = filters.map(filter => {
  712. if (/^\d+$/.test(filter)) {
  713. return Number(filter)
  714. } else {
  715. return filter
  716. }
  717. });
  718.  
  719. helper.config.findComponentsFilters = filters;
  720.  
  721. const result = {
  722. components: [],
  723. globalComponents: [],
  724. destroyedComponents: []
  725. };
  726.  
  727. /* 在helper.components里进行组件查找 */
  728. const components = helper.components;
  729. const keys = Object.keys(components);
  730. for (let i = 0; i < keys.length; i++) {
  731. const component = components[keys[i]];
  732.  
  733. for (let j = 0; j < filters.length; j++) {
  734. const filter = filters[j];
  735.  
  736. if (typeof filter === 'number' && component._uid === filter) {
  737. result.components.push(component);
  738. break
  739. } else if (typeof filter === 'string') {
  740. const { _componentTag, _componentName } = component;
  741.  
  742. if (String(_componentTag).includes(filter) || String(_componentName).includes(filter)) {
  743. result.components.push(component);
  744. break
  745. }
  746. }
  747. }
  748. }
  749.  
  750. /* 进行全局组件查找 */
  751. const globalComponentsKeys = Object.keys(helper.Vue.options.components);
  752. for (let i = 0; i < globalComponentsKeys.length; i++) {
  753. const key = String(globalComponentsKeys[i]);
  754. const component = helper.Vue.options.components[globalComponentsKeys[i]];
  755.  
  756. for (let j = 0; j < filters.length; j++) {
  757. const filter = filters[j];
  758. if (key.includes(filter)) {
  759. const tmpObj = {};
  760. tmpObj[key] = component;
  761. result.globalComponents.push(tmpObj);
  762. break
  763. }
  764. }
  765. }
  766.  
  767. helper.destroyList.forEach(item => {
  768. for (let j = 0; j < filters.length; j++) {
  769. const filter = filters[j];
  770.  
  771. if (typeof filter === 'number' && item.uid === filter) {
  772. result.destroyedComponents.push(item);
  773. break
  774. } else if (typeof filter === 'string') {
  775. if (String(item.tag).includes(filter) || String(item.name).includes(filter)) {
  776. result.destroyedComponents.push(item);
  777. break
  778. }
  779. }
  780. }
  781. });
  782.  
  783. return result
  784. },
  785.  
  786. findNotContainElementComponents () {
  787. const result = [];
  788. const keys = Object.keys(helper.components);
  789. keys.forEach(key => {
  790. const component = helper.components[key];
  791. const elStr = Object.prototype.toString.call(component.$el);
  792. if (!/(HTML|Comment)/.test(elStr)) {
  793. result.push(component);
  794. }
  795. });
  796.  
  797. return result
  798. },
  799.  
  800. /**
  801. * 阻止组件的创建
  802. * @param {string|array} filters 组件名称过滤器,可以是字符串或者数组,如果是字符串多个过滤选可用,或|分隔
  803. */
  804. blockComponents (filters) {
  805. filters = toArrFilters(filters);
  806. helper.config.blockFilters = filters;
  807. },
  808.  
  809. /**
  810. * 给指定组件注入大量空数据,以便观察组件的内存泄露情况
  811. * @param {Array|string} filter -必选 指定组件的名称,如果为空则表示注入所有组件
  812. * @param {number} count -可选 指定注入空数据的大小,单位Kb,默认为1024Kb,即1Mb
  813. * @returns
  814. */
  815. dd (filter, count = 1024) {
  816. filter = toArrFilters(filter);
  817. helper.config.dd = {
  818. enabled: true,
  819. filters: filter,
  820. count
  821. };
  822. },
  823. /* 禁止给组件注入空数据 */
  824. undd () {
  825. helper.config.dd = {
  826. enabled: false,
  827. filters: [],
  828. count: 1024
  829. };
  830.  
  831. /* 删除之前注入的数据 */
  832. Object.keys(helper.components).forEach(key => {
  833. const component = helper.components[key];
  834. component.$data && delete component.$data.__dd__;
  835. });
  836. },
  837.  
  838. toggleDevtools () {
  839. helper.config.devtools = !helper.config.devtools;
  840. },
  841.  
  842. /* 对Vue.component进行hack,以便观察什么时候进行了哪些全局组件的注册操作 */
  843. hackVueComponent (callback) {
  844. if (!helper.Vue || !(helper.Vue.component instanceof Function) || helper._vueComponentOrgin_) {
  845. debug.log(i18n.t('debugHelper.hackVueComponent.hack') + ' (failed)');
  846. return false
  847. }
  848.  
  849. const vueComponentOrgin = helper.Vue.component;
  850.  
  851. helper.Vue.component = function (name, opts) {
  852. if (callback instanceof Function) {
  853. callback.apply(helper.Vue, arguments);
  854. } else {
  855. if (helper.Vue.options.components[name]) {
  856. debug.warn(`[Vue.component][REPEAT][old-cid:${helper.Vue.options.components[name].cid}]`, name, opts);
  857. } else {
  858. debug.log('[Vue.component]', name, opts);
  859. }
  860. }
  861.  
  862. return vueComponentOrgin.apply(helper.Vue, arguments)
  863. };
  864.  
  865. helper._vueComponentOrgin_ = vueComponentOrgin;
  866. debug.log(i18n.t('debugHelper.hackVueComponent.hack') + ' (success)');
  867. return true
  868. },
  869.  
  870. unHackVueComponent () {
  871. if (helper._vueComponentOrgin_ && helper.Vue) {
  872. helper.Vue.component = helper._vueComponentOrgin_;
  873. delete helper._vueComponentOrgin_;
  874. debug.log(i18n.t('debugHelper.hackVueComponent.unhack') + ' (success)');
  875. return true
  876. }
  877. }
  878. };
  879.  
  880. helper.methods = methods;
  881.  
  882. /*!
  883. * @name index.js
  884. * @description hookJs JS AOP切面编程辅助库
  885. * @version 0.0.1
  886. * @author Blaze
  887. * @date 2020/10/22 17:40
  888. * @github https://github.com/xxxily
  889. */
  890.  
  891. const win = typeof window === 'undefined' ? global : window;
  892. const toStr = Function.prototype.call.bind(Object.prototype.toString);
  893. /* 特殊场景,如果把Boolean也hook了,很容易导致调用溢出,所以是需要使用原生Boolean */
  894. const toBoolean = Boolean.originMethod ? Boolean.originMethod : Boolean;
  895. const util = {
  896. toStr,
  897. isObj: obj => toStr(obj) === '[object Object]',
  898. /* 判断是否为引用类型,用于更宽泛的场景 */
  899. isRef: obj => typeof obj === 'object',
  900. isReg: obj => toStr(obj) === '[object RegExp]',
  901. isFn: obj => obj instanceof Function,
  902. isAsyncFn: fn => toStr(fn) === '[object AsyncFunction]',
  903. isPromise: obj => toStr(obj) === '[object Promise]',
  904. firstUpperCase: str => str.replace(/^\S/, s => s.toUpperCase()),
  905. toArr: arg => Array.from(Array.isArray(arg) ? arg : [arg]),
  906.  
  907. debug: {
  908. log () {
  909. let log = win.console.log;
  910. /* 如果log也被hook了,则使用未被hook前的log函数 */
  911. if (log.originMethod) { log = log.originMethod; }
  912. if (win._debugMode_) {
  913. log.apply(win.console, arguments);
  914. }
  915. }
  916. },
  917. /* 获取包含自身、继承、可枚举、不可枚举的键名 */
  918. getAllKeys (obj) {
  919. const tmpArr = [];
  920. for (const key in obj) { tmpArr.push(key); }
  921. const allKeys = Array.from(new Set(tmpArr.concat(Reflect.ownKeys(obj))));
  922. return allKeys
  923. }
  924. };
  925.  
  926. class HookJs {
  927. constructor (useProxy) {
  928. this.useProxy = useProxy || false;
  929. this.hookPropertiesKeyName = '_hookProperties' + Date.now();
  930. }
  931.  
  932. hookJsPro () {
  933. return new HookJs(true)
  934. }
  935.  
  936. _addHook (hookMethod, fn, type, classHook) {
  937. const hookKeyName = type + 'Hooks';
  938. const hookMethodProperties = hookMethod[this.hookPropertiesKeyName];
  939. if (!hookMethodProperties[hookKeyName]) {
  940. hookMethodProperties[hookKeyName] = [];
  941. }
  942.  
  943. /* 注册(储存)要被调用的hook函数,同时防止重复注册 */
  944. let hasSameHook = false;
  945. for (let i = 0; i < hookMethodProperties[hookKeyName].length; i++) {
  946. if (fn === hookMethodProperties[hookKeyName][i]) {
  947. hasSameHook = true;
  948. break
  949. }
  950. }
  951.  
  952. if (!hasSameHook) {
  953. fn.classHook = classHook || false;
  954. hookMethodProperties[hookKeyName].push(fn);
  955. }
  956. }
  957.  
  958. _runHooks (parentObj, methodName, originMethod, hookMethod, target, ctx, args, classHook, hookPropertiesKeyName) {
  959. const hookMethodProperties = hookMethod[hookPropertiesKeyName];
  960. const beforeHooks = hookMethodProperties.beforeHooks || [];
  961. const afterHooks = hookMethodProperties.afterHooks || [];
  962. const errorHooks = hookMethodProperties.errorHooks || [];
  963. const hangUpHooks = hookMethodProperties.hangUpHooks || [];
  964. const replaceHooks = hookMethodProperties.replaceHooks || [];
  965. const execInfo = {
  966. result: null,
  967. error: null,
  968. args: args,
  969. type: ''
  970. };
  971.  
  972. function runHooks (hooks, type) {
  973. let hookResult = null;
  974. execInfo.type = type || '';
  975. if (Array.isArray(hooks)) {
  976. hooks.forEach(fn => {
  977. if (util.isFn(fn) && classHook === fn.classHook) {
  978. hookResult = fn(args, parentObj, methodName, originMethod, execInfo, ctx);
  979. }
  980. });
  981. }
  982. return hookResult
  983. }
  984.  
  985. const runTarget = (function () {
  986. if (classHook) {
  987. return function () {
  988. // eslint-disable-next-line new-cap
  989. return new target(...args)
  990. }
  991. } else {
  992. return function () {
  993. return target.apply(ctx, args)
  994. }
  995. }
  996. })();
  997.  
  998. const beforeHooksResult = runHooks(beforeHooks, 'before');
  999. /* 支持终止后续调用的指令 */
  1000. if (beforeHooksResult && beforeHooksResult === 'STOP-INVOKE') {
  1001. return beforeHooksResult
  1002. }
  1003.  
  1004. if (hangUpHooks.length || replaceHooks.length) {
  1005. /**
  1006. * 当存在hangUpHooks或replaceHooks的时候是不会触发原来函数的
  1007. * 本质上来说hangUpHooks和replaceHooks是一样的,只是外部的定义描述不一致和分类不一致而已
  1008. */
  1009. runHooks(hangUpHooks, 'hangUp');
  1010. runHooks(replaceHooks, 'replace');
  1011. } else {
  1012. if (errorHooks.length) {
  1013. try {
  1014. execInfo.result = runTarget();
  1015. } catch (err) {
  1016. execInfo.error = err;
  1017. const errorHooksResult = runHooks(errorHooks, 'error');
  1018. /* 支持执行错误后不抛出异常的指令 */
  1019. if (errorHooksResult && errorHooksResult === 'SKIP-ERROR') ; else {
  1020. throw err
  1021. }
  1022. }
  1023. } else {
  1024. execInfo.result = runTarget();
  1025. }
  1026. }
  1027.  
  1028. /**
  1029. * 执行afterHooks,如果返回的是Promise,理论上应该进行进一步的细分处理
  1030. * 但添加细分处理逻辑后发现性能下降得比较厉害,且容易出现各种异常,所以决定不在hook里处理Promise情况
  1031. * 下面是原Promise处理逻辑,添加后会导致以下网站卡死或无法访问:
  1032. * wenku.baidu.com
  1033. * https://pubs.rsc.org/en/content/articlelanding/2021/sc/d1sc01881g#!divAbstract
  1034. * https://www.elsevier.com/connect/coronavirus-information-center
  1035. */
  1036. // if (execInfo.result && execInfo.result.then && util.isPromise(execInfo.result)) {
  1037. // execInfo.result.then(function (data) {
  1038. // execInfo.result = data
  1039. // runHooks(afterHooks, 'after')
  1040. // return Promise.resolve.apply(ctx, arguments)
  1041. // }).catch(function (err) {
  1042. // execInfo.error = err
  1043. // runHooks(errorHooks, 'error')
  1044. // return Promise.reject.apply(ctx, arguments)
  1045. // })
  1046. // }
  1047.  
  1048. runHooks(afterHooks, 'after');
  1049.  
  1050. return execInfo.result
  1051. }
  1052.  
  1053. _proxyMethodcGenerator (parentObj, methodName, originMethod, classHook, context, proxyHandler) {
  1054. const t = this;
  1055. const useProxy = t.useProxy;
  1056. let hookMethod = null;
  1057.  
  1058. /* 存在缓存则使用缓存的hookMethod */
  1059. if (t.isHook(originMethod)) {
  1060. hookMethod = originMethod;
  1061. } else if (originMethod[t.hookPropertiesKeyName] && t.isHook(originMethod[t.hookPropertiesKeyName].hookMethod)) {
  1062. hookMethod = originMethod[t.hookPropertiesKeyName].hookMethod;
  1063. }
  1064.  
  1065. if (hookMethod) {
  1066. if (!hookMethod[t.hookPropertiesKeyName].isHook) {
  1067. /* 重新标注被hook状态 */
  1068. hookMethod[t.hookPropertiesKeyName].isHook = true;
  1069. util.debug.log(`[hook method] ${util.toStr(parentObj)} ${methodName}`);
  1070. }
  1071. return hookMethod
  1072. }
  1073.  
  1074. /* 使用Proxy模式进行hook可以获得更多特性,但性能也会稍差一些 */
  1075. if (useProxy && Proxy) {
  1076. /* 注意:使用Proxy代理,hookMethod和originMethod将共用同一对象 */
  1077. const handler = { ...proxyHandler };
  1078.  
  1079. /* 下面的写法确定了proxyHandler是无法覆盖construct和apply操作的 */
  1080. if (classHook) {
  1081. handler.construct = function (target, args, newTarget) {
  1082. context = context || this;
  1083. return t._runHooks(parentObj, methodName, originMethod, hookMethod, target, context, args, true, t.hookPropertiesKeyName)
  1084. };
  1085. } else {
  1086. handler.apply = function (target, ctx, args) {
  1087. ctx = context || ctx;
  1088. return t._runHooks(parentObj, methodName, originMethod, hookMethod, target, ctx, args, false, t.hookPropertiesKeyName)
  1089. };
  1090. }
  1091.  
  1092. hookMethod = new Proxy(originMethod, handler);
  1093. } else {
  1094. hookMethod = function () {
  1095. /**
  1096. * 注意此处不能通过 context = context || this
  1097. * 然后通过把context当ctx传递过去
  1098. * 这将导致ctx引用错误
  1099. */
  1100. const ctx = context || this;
  1101. return t._runHooks(parentObj, methodName, originMethod, hookMethod, originMethod, ctx, arguments, classHook, t.hookPropertiesKeyName)
  1102. };
  1103.  
  1104. /* 确保子对象和原型链跟originMethod保持一致 */
  1105. const keys = Reflect.ownKeys(originMethod);
  1106. keys.forEach(keyName => {
  1107. Object.defineProperty(hookMethod, keyName, {
  1108. get: function () {
  1109. return originMethod[keyName]
  1110. },
  1111. set: function (val) {
  1112. originMethod[keyName] = val;
  1113. }
  1114. });
  1115. });
  1116. hookMethod.prototype = originMethod.prototype;
  1117. }
  1118.  
  1119. const hookMethodProperties = hookMethod[t.hookPropertiesKeyName] = {};
  1120.  
  1121. hookMethodProperties.originMethod = originMethod;
  1122. hookMethodProperties.hookMethod = hookMethod;
  1123. hookMethodProperties.isHook = true;
  1124. hookMethodProperties.classHook = classHook;
  1125.  
  1126. util.debug.log(`[hook method] ${util.toStr(parentObj)} ${methodName}`);
  1127.  
  1128. return hookMethod
  1129. }
  1130.  
  1131. _getObjKeysByRule (obj, rule) {
  1132. let excludeRule = null;
  1133. let result = rule;
  1134.  
  1135. if (util.isObj(rule) && rule.include) {
  1136. excludeRule = rule.exclude;
  1137. rule = rule.include;
  1138. result = rule;
  1139. }
  1140.  
  1141. /**
  1142. * for in、Object.keys与Reflect.ownKeys的区别见:
  1143. * https://es6.ruanyifeng.com/#docs/object#%E5%B1%9E%E6%80%A7%E7%9A%84%E9%81%8D%E5%8E%86
  1144. */
  1145. if (rule === '*') {
  1146. result = Object.keys(obj);
  1147. } else if (rule === '**') {
  1148. result = Reflect.ownKeys(obj);
  1149. } else if (rule === '***') {
  1150. result = util.getAllKeys(obj);
  1151. } else if (util.isReg(rule)) {
  1152. result = util.getAllKeys(obj).filter(keyName => rule.test(keyName));
  1153. }
  1154.  
  1155. /* 如果存在排除规则,则需要进行排除 */
  1156. if (excludeRule) {
  1157. result = Array.isArray(result) ? result : [result];
  1158. if (util.isReg(excludeRule)) {
  1159. result = result.filter(keyName => !excludeRule.test(keyName));
  1160. } else if (Array.isArray(excludeRule)) {
  1161. result = result.filter(keyName => !excludeRule.includes(keyName));
  1162. } else {
  1163. result = result.filter(keyName => excludeRule !== keyName);
  1164. }
  1165. }
  1166.  
  1167. return util.toArr(result)
  1168. }
  1169.  
  1170. /**
  1171. * 判断某个函数是否已经被hook
  1172. * @param fn {Function} -必选 要判断的函数
  1173. * @returns {boolean}
  1174. */
  1175. isHook (fn) {
  1176. if (!fn || !fn[this.hookPropertiesKeyName]) {
  1177. return false
  1178. }
  1179. const hookMethodProperties = fn[this.hookPropertiesKeyName];
  1180. return util.isFn(hookMethodProperties.originMethod) && fn !== hookMethodProperties.originMethod
  1181. }
  1182.  
  1183. /**
  1184. * 判断对象下的某个值是否具备hook的条件
  1185. * 注意:具备hook条件和能否直接修改值是两回事,
  1186. * 在进行hook的时候还要检查descriptor.writable是否为false
  1187. * 如果为false则要修改成true才能hook成功
  1188. * @param parentObj
  1189. * @param keyName
  1190. * @returns {boolean}
  1191. */
  1192. isAllowHook (parentObj, keyName) {
  1193. /* 有些对象会设置getter,让读取值的时候就抛错,所以需要try catch 判断能否正常读取属性 */
  1194. try { if (!parentObj[keyName]) return false } catch (e) { return false }
  1195. const descriptor = Object.getOwnPropertyDescriptor(parentObj, keyName);
  1196. return !(descriptor && descriptor.configurable === false)
  1197. }
  1198.  
  1199. /**
  1200. * hook 核心函数
  1201. * @param parentObj {Object} -必选 被hook函数依赖的父对象
  1202. * @param hookMethods {Object|Array|RegExp|string} -必选 被hook函数的函数名或函数名的匹配规则
  1203. * @param fn {Function} -必选 hook之后的回调方法
  1204. * @param type {String} -可选 默认before,指定运行hook函数回调的时机,可选字符串:before、after、replace、error、hangUp
  1205. * @param classHook {Boolean} -可选 默认false,指定是否为针对new(class)操作的hook
  1206. * @param context {Object} -可选 指定运行被hook函数时的上下文对象
  1207. * @param proxyHandler {Object} -可选 仅当用Proxy进行hook时有效,默认使用的是Proxy的apply handler进行hook,如果你有特殊需求也可以配置自己的handler以实现更复杂的功能
  1208. * 附注:不使用Proxy进行hook,可以获得更高性能,但也意味着通用性更差些,对于要hook HTMLElement.prototype、EventTarget.prototype这些对象里面的非实例的函数往往会失败而导致被hook函数执行出错
  1209. * @returns {boolean}
  1210. */
  1211. hook (parentObj, hookMethods, fn, type, classHook, context, proxyHandler) {
  1212. classHook = toBoolean(classHook);
  1213. type = type || 'before';
  1214.  
  1215. if ((!util.isRef(parentObj) && !util.isFn(parentObj)) || !util.isFn(fn) || !hookMethods) {
  1216. return false
  1217. }
  1218.  
  1219. const t = this;
  1220.  
  1221. hookMethods = t._getObjKeysByRule(parentObj, hookMethods);
  1222. hookMethods.forEach(methodName => {
  1223. if (!t.isAllowHook(parentObj, methodName)) {
  1224. util.debug.log(`${util.toStr(parentObj)} [${methodName}] does not support modification`);
  1225. return false
  1226. }
  1227.  
  1228. const descriptor = Object.getOwnPropertyDescriptor(parentObj, methodName);
  1229. if (descriptor && descriptor.writable === false) {
  1230. Object.defineProperty(parentObj, methodName, { writable: true });
  1231. }
  1232.  
  1233. const originMethod = parentObj[methodName];
  1234. let hookMethod = null;
  1235.  
  1236. /* 非函数无法进行hook操作 */
  1237. if (!util.isFn(originMethod)) {
  1238. return false
  1239. }
  1240.  
  1241. hookMethod = t._proxyMethodcGenerator(parentObj, methodName, originMethod, classHook, context, proxyHandler);
  1242.  
  1243. const hookMethodProperties = hookMethod[t.hookPropertiesKeyName];
  1244. if (hookMethodProperties.classHook !== classHook) {
  1245. util.debug.log(`${util.toStr(parentObj)} [${methodName}] Cannot support functions hook and classes hook at the same time `);
  1246. return false
  1247. }
  1248.  
  1249. /* 使用hookMethod接管需要被hook的方法 */
  1250. if (parentObj[methodName] !== hookMethod) {
  1251. parentObj[methodName] = hookMethod;
  1252. }
  1253.  
  1254. t._addHook(hookMethod, fn, type, classHook);
  1255. });
  1256. }
  1257.  
  1258. /* 专门针对new操作的hook,本质上是hook函数的别名,可以少传classHook这个参数,并且明确语义 */
  1259. hookClass (parentObj, hookMethods, fn, type, context, proxyHandler) {
  1260. return this.hook(parentObj, hookMethods, fn, type, true, context, proxyHandler)
  1261. }
  1262.  
  1263. /**
  1264. * 取消对某个函数的hook
  1265. * @param parentObj {Object} -必选 要取消被hook函数依赖的父对象
  1266. * @param hookMethods {Object|Array|RegExp|string} -必选 要取消被hook函数的函数名或函数名的匹配规则
  1267. * @param type {String} -可选 默认before,指定要取消的hook类型,可选字符串:before、after、replace、error、hangUp,如果不指定该选项则取消所有类型下的所有回调
  1268. * @param fn {Function} -必选 取消指定的hook回调函数,如果不指定该选项则取消对应type类型下的所有回调
  1269. * @returns {boolean}
  1270. */
  1271. unHook (parentObj, hookMethods, type, fn) {
  1272. if (!util.isRef(parentObj) || !hookMethods) {
  1273. return false
  1274. }
  1275.  
  1276. const t = this;
  1277. hookMethods = t._getObjKeysByRule(parentObj, hookMethods);
  1278. hookMethods.forEach(methodName => {
  1279. if (!t.isAllowHook(parentObj, methodName)) {
  1280. return false
  1281. }
  1282.  
  1283. const hookMethod = parentObj[methodName];
  1284.  
  1285. if (!t.isHook(hookMethod)) {
  1286. return false
  1287. }
  1288.  
  1289. const hookMethodProperties = hookMethod[t.hookPropertiesKeyName];
  1290. const originMethod = hookMethodProperties.originMethod;
  1291.  
  1292. if (type) {
  1293. const hookKeyName = type + 'Hooks';
  1294. const hooks = hookMethodProperties[hookKeyName] || [];
  1295.  
  1296. if (fn) {
  1297. /* 删除指定类型下的指定hook函数 */
  1298. for (let i = 0; i < hooks.length; i++) {
  1299. if (fn === hooks[i]) {
  1300. hookMethodProperties[hookKeyName].splice(i, 1);
  1301. util.debug.log(`[unHook ${hookKeyName} func] ${util.toStr(parentObj)} ${methodName}`, fn);
  1302. break
  1303. }
  1304. }
  1305. } else {
  1306. /* 删除指定类型下的所有hook函数 */
  1307. if (Array.isArray(hookMethodProperties[hookKeyName])) {
  1308. hookMethodProperties[hookKeyName] = [];
  1309. util.debug.log(`[unHook all ${hookKeyName}] ${util.toStr(parentObj)} ${methodName}`);
  1310. }
  1311. }
  1312. } else {
  1313. /* 彻底还原被hook的函数 */
  1314. if (util.isFn(originMethod)) {
  1315. parentObj[methodName] = originMethod;
  1316. delete parentObj[methodName][t.hookPropertiesKeyName];
  1317.  
  1318. // Object.keys(hookMethod).forEach(keyName => {
  1319. // if (/Hooks$/.test(keyName) && Array.isArray(hookMethod[keyName])) {
  1320. // hookMethod[keyName] = []
  1321. // }
  1322. // })
  1323. //
  1324. // hookMethod.isHook = false
  1325. // parentObj[methodName] = originMethod
  1326. // delete parentObj[methodName].originMethod
  1327. // delete parentObj[methodName].hookMethod
  1328. // delete parentObj[methodName].isHook
  1329. // delete parentObj[methodName].isClassHook
  1330.  
  1331. util.debug.log(`[unHook method] ${util.toStr(parentObj)} ${methodName}`);
  1332. }
  1333. }
  1334. });
  1335. }
  1336.  
  1337. /* 源函数运行前的hook */
  1338. before (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1339. return this.hook(obj, hookMethods, fn, 'before', classHook, context, proxyHandler)
  1340. }
  1341.  
  1342. /* 源函数运行后的hook */
  1343. after (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1344. return this.hook(obj, hookMethods, fn, 'after', classHook, context, proxyHandler)
  1345. }
  1346.  
  1347. /* 替换掉要hook的函数,不再运行源函数,换成运行其他逻辑 */
  1348. replace (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1349. return this.hook(obj, hookMethods, fn, 'replace', classHook, context, proxyHandler)
  1350. }
  1351.  
  1352. /* 源函数运行出错时的hook */
  1353. error (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1354. return this.hook(obj, hookMethods, fn, 'error', classHook, context, proxyHandler)
  1355. }
  1356.  
  1357. /* 底层实现逻辑与replace一样,都是替换掉要hook的函数,不再运行源函数,只不过是为了明确语义,将源函数挂起不再执行,原则上也不再执行其他逻辑,如果要执行其他逻辑请使用replace hook */
  1358. hangUp (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1359. return this.hook(obj, hookMethods, fn, 'hangUp', classHook, context, proxyHandler)
  1360. }
  1361. }
  1362.  
  1363. var hookJs = new HookJs();
  1364.  
  1365. /**
  1366. * 打印生命周期信息
  1367. * @param {Vue} vm vue组件实例
  1368. * @param {string} lifeCycle vue生命周期名称
  1369. * @returns
  1370. */
  1371. function printLifeCycle (vm, lifeCycle) {
  1372. const lifeCycleConf = helper.config.lifecycle || { show: false, filters: ['created'], componentFilters: [] };
  1373.  
  1374. if (!vm || !lifeCycle || !lifeCycleConf.show) {
  1375. return false
  1376. }
  1377.  
  1378. const { _componentTag, _componentName, _componentChain, _createdHumanTime, _uid } = vm;
  1379. const info = `[${lifeCycle}] tag: ${_componentTag}, uid: ${_uid}, createdTime: ${_createdHumanTime}, chain: ${_componentChain}`;
  1380. const matchComponentFilters = lifeCycleConf.componentFilters.length === 0 || lifeCycleConf.componentFilters.includes(_componentName);
  1381.  
  1382. if (lifeCycleConf.filters.includes(lifeCycle) && matchComponentFilters) {
  1383. debug.log(info);
  1384. }
  1385. }
  1386.  
  1387. function mixinRegister (Vue) {
  1388. if (!Vue || !Vue.mixin) {
  1389. debug.error('未检查到VUE对象,请检查是否引入了VUE,且将VUE对象挂载到全局变量window.Vue上');
  1390. return false
  1391. }
  1392.  
  1393. /* 自动开启Vue的调试模式 */
  1394. if (Vue.config) {
  1395. if (helper.config.devtools) {
  1396. Vue.config.debug = true;
  1397. Vue.config.devtools = true;
  1398. Vue.config.performance = true;
  1399.  
  1400. setTimeout(() => {
  1401. const devtools = getVueDevtools();
  1402. if (devtools) {
  1403. if (!devtools.enabled) {
  1404. devtools.emit('init', Vue);
  1405. debug.info('vue devtools init emit.');
  1406. }
  1407. } else {
  1408. // debug.info(
  1409. // 'Download the Vue Devtools extension for a better development experience:\n' +
  1410. // 'https://github.com/vuejs/vue-devtools'
  1411. // )
  1412. debug.info('vue devtools check failed.');
  1413. }
  1414. }, 200);
  1415. } else {
  1416. Vue.config.debug = false;
  1417. Vue.config.devtools = false;
  1418. Vue.config.performance = false;
  1419. }
  1420. } else {
  1421. debug.log('Vue.config is not defined');
  1422. }
  1423.  
  1424. if (helper.config.hackVueComponent) {
  1425. helper.methods.hackVueComponent();
  1426. }
  1427.  
  1428. /* 使用AOP对Vue.extend进行切面阻断组件的创建 */
  1429. const hookJsPro = hookJs.hookJsPro();
  1430.  
  1431. hookJsPro.before(Vue, 'extend', (args, parentObj, methodName, originMethod, execInfo, ctx) => {
  1432. const extendOpts = args[0];
  1433. // debug.warn('extendOptions:', extendOpts.name || 'unknown')
  1434.  
  1435. const hasBlockFilter = helper.config.blockFilters && helper.config.blockFilters.length;
  1436. if (hasBlockFilter && extendOpts.name && filtersMatch(helper.config.blockFilters, extendOpts.name)) {
  1437. debug.info(`[block component]: name: ${extendOpts.name}`);
  1438. return 'STOP-INVOKE'
  1439. }
  1440. });
  1441.  
  1442. /* 禁止因为阻断组件的创建而导致的错误提示输出,减少不必要的信息噪音 */
  1443. hookJsPro.before(Vue.util, 'warn', (args) => {
  1444. const msg = args[0];
  1445. if (msg.includes('STOP-INVOKE')) {
  1446. return 'STOP-INVOKE'
  1447. }
  1448. });
  1449.  
  1450. Vue.mixin({
  1451. beforeCreate: function () {
  1452. // const tag = this.$options?._componentTag || this.$vnode?.tag || this._uid
  1453. const tag = this.$vnode?.tag || this.$options?._componentTag || this._uid;
  1454. const chain = helper.methods.getComponentChain(this);
  1455. this._componentTag = tag;
  1456. this._componentChain = chain;
  1457. this._componentName = isNaN(Number(tag)) ? tag.replace(/^vue-component-\d+-/, '') : 'anonymous-component';
  1458. this._createdTime = Date.now();
  1459.  
  1460. /* 增加人类方便查看的时间信息 */
  1461. const timeObj = new Date(this._createdTime);
  1462. this._createdHumanTime = `${timeObj.getHours()}:${timeObj.getMinutes()}:${timeObj.getSeconds()}`;
  1463.  
  1464. /* 判断是否为函数式组件,函数式组件无状态 (没有响应式数据),也没有实例,也没生命周期概念 */
  1465. if (this._componentName === 'anonymous-component' && !this.$parent && !this.$vnode) {
  1466. this._componentName = 'functional-component';
  1467. }
  1468.  
  1469. helper.components[this._uid] = this;
  1470.  
  1471. /**
  1472. * 收集所有创建过的组件信息,此处只存储组件的基础信息,没销毁的组件会包含组件实例
  1473. * 严禁对组件内其它对象进行引用,否则会导致组件实列无法被正常回收
  1474. */
  1475. const componentSummary = {
  1476. uid: this._uid,
  1477. name: this._componentName,
  1478. tag: this._componentTag,
  1479. createdTime: this._createdTime,
  1480. createdHumanTime: this._createdHumanTime,
  1481. // 0 表示还没被销毁
  1482. destroyTime: 0,
  1483. // 0 表示还没被销毁,duration可持续当当前查看时间
  1484. duration: 0,
  1485. component: this,
  1486. chain
  1487. };
  1488. helper.componentsSummary[this._uid] = componentSummary;
  1489.  
  1490. /* 添加到componentsSummaryStatistics里,生成统计信息 */
  1491. Array.isArray(helper.componentsSummaryStatistics[this._componentName])
  1492. ? helper.componentsSummaryStatistics[this._componentName].push(componentSummary)
  1493. : (helper.componentsSummaryStatistics[this._componentName] = [componentSummary]);
  1494.  
  1495. printLifeCycle(this, 'beforeCreate');
  1496. },
  1497. created: function () {
  1498. /* 增加空白数据,方便观察内存泄露情况 */
  1499. if (helper.config.dd.enabled) {
  1500. let needDd = false;
  1501.  
  1502. if (helper.config.dd.filters.length === 0) {
  1503. needDd = true;
  1504. } else {
  1505. for (let index = 0; index < helper.config.dd.filters.length; index++) {
  1506. const filter = helper.config.dd.filters[index];
  1507. if (filter === this._componentName || String(this._componentName).endsWith(filter)) {
  1508. needDd = true;
  1509. break
  1510. }
  1511. }
  1512. }
  1513.  
  1514. if (needDd) {
  1515. const count = helper.config.dd.count * 1024;
  1516. const componentInfo = `tag: ${this._componentTag}, uid: ${this._uid}, createdTime: ${this._createdHumanTime}`;
  1517.  
  1518. /* 此处必须使用JSON.stringify对产生的字符串进行消费,否则没法将内存占用上去 */
  1519. this.$data.__dd__ = JSON.stringify(componentInfo + ' ' + helper.methods.createEmptyData(count, this._uid));
  1520.  
  1521. console.log(`[dd success] ${componentInfo} chain: ${this._componentChain}`);
  1522. }
  1523. }
  1524.  
  1525. printLifeCycle(this, 'created');
  1526. },
  1527. beforeMount: function () {
  1528. printLifeCycle(this, 'beforeMount');
  1529. },
  1530. mounted: function () {
  1531. printLifeCycle(this, 'mounted');
  1532. },
  1533. beforeUpdate: function () {
  1534. printLifeCycle(this, 'beforeUpdate');
  1535. },
  1536. activated: function () {
  1537. printLifeCycle(this, 'activated');
  1538. },
  1539. deactivated: function () {
  1540. printLifeCycle(this, 'deactivated');
  1541. },
  1542. updated: function () {
  1543. printLifeCycle(this, 'updated');
  1544. },
  1545. beforeDestroy: function () {
  1546. printLifeCycle(this, 'beforeDestroy');
  1547. },
  1548. destroyed: function () {
  1549. printLifeCycle(this, 'destroyed');
  1550.  
  1551. if (this._componentTag) {
  1552. const uid = this._uid;
  1553. const name = this._componentName;
  1554. const destroyTime = Date.now();
  1555.  
  1556. /* helper里的componentSummary有可能通过调用clear函数而被清除掉,所以需进行判断再更新赋值 */
  1557. const componentSummary = helper.componentsSummary[this._uid];
  1558. if (componentSummary) {
  1559. /* 补充/更新组件信息 */
  1560. componentSummary.destroyTime = destroyTime;
  1561. componentSummary.duration = destroyTime - this._createdTime;
  1562.  
  1563. helper.destroyList.push(componentSummary);
  1564.  
  1565. /* 统计被销毁的组件信息 */
  1566. Array.isArray(helper.destroyStatistics[name])
  1567. ? helper.destroyStatistics[name].push(componentSummary)
  1568. : (helper.destroyStatistics[name] = [componentSummary]);
  1569.  
  1570. /* 删除已销毁的组件实例 */
  1571. delete componentSummary.component;
  1572. }
  1573.  
  1574. // 解除引用关系
  1575. delete this._componentTag;
  1576. delete this._componentChain;
  1577. delete this._componentName;
  1578. delete this._createdTime;
  1579. delete this._createdHumanTime;
  1580. delete this.$data.__dd__;
  1581. delete helper.components[uid];
  1582. } else {
  1583. console.error('存在未被正常标记的组件,请检查组件采集逻辑是否需完善', this);
  1584. }
  1585. }
  1586. });
  1587. }
  1588.  
  1589. /*!
  1590. * @name menuCommand.js
  1591. * @version 0.0.1
  1592. * @author Blaze
  1593. * @date 2019/9/21 14:22
  1594. */
  1595.  
  1596. const monkeyMenu = {
  1597. on (title, fn, accessKey) {
  1598. return window.GM_registerMenuCommand && window.GM_registerMenuCommand(title, fn, accessKey)
  1599. },
  1600. off (id) {
  1601. return window.GM_unregisterMenuCommand && window.GM_unregisterMenuCommand(id)
  1602. },
  1603. /* 切换类型的菜单功能 */
  1604. switch (title, fn, defVal) {
  1605. const t = this;
  1606. t.on(title, fn);
  1607. }
  1608. };
  1609.  
  1610. /*!
  1611. * @name functionCall.js
  1612. * @description 统一的提供外部功能调用管理模块
  1613. * @version 0.0.1
  1614. * @author xxxily
  1615. * @date 2022/04/27 17:42
  1616. * @github https://github.com/xxxily
  1617. */
  1618.  
  1619. const functionCall = {
  1620. viewVueDebugHelperObject () {
  1621. debug.log(i18n.t('debugHelper.viewVueDebugHelperObject'), helper);
  1622. },
  1623. componentsStatistics () {
  1624. const result = helper.methods.componentsStatistics();
  1625. let total = 0;
  1626.  
  1627. /* 提供友好的可视化展示方式 */
  1628. console.table && console.table(result.map(item => {
  1629. total += item.componentInstance.length;
  1630. return {
  1631. componentName: item.componentName,
  1632. count: item.componentInstance.length
  1633. }
  1634. }));
  1635.  
  1636. debug.log(`${i18n.t('debugHelper.componentsStatistics')} (total:${total})`, result);
  1637. },
  1638. destroyStatisticsSort () {
  1639. const result = helper.methods.destroyStatisticsSort();
  1640. let total = 0;
  1641.  
  1642. /* 提供友好的可视化展示方式 */
  1643. console.table && console.table(result.map(item => {
  1644. const durationList = item.destroyList.map(item => item.duration);
  1645. const maxDuration = Math.max(...durationList);
  1646. const minDuration = Math.min(...durationList);
  1647. const durationRange = maxDuration - minDuration;
  1648. total += item.destroyList.length;
  1649.  
  1650. return {
  1651. componentName: item.componentName,
  1652. count: item.destroyList.length,
  1653. avgDuration: durationList.reduce((pre, cur) => pre + cur, 0) / durationList.length,
  1654. maxDuration,
  1655. minDuration,
  1656. durationRange,
  1657. durationRangePercent: (1000 - minDuration) / durationRange
  1658. }
  1659. }));
  1660.  
  1661. debug.log(`${i18n.t('debugHelper.destroyStatisticsSort')} (total:${total})`, result);
  1662. },
  1663. componentsSummaryStatisticsSort () {
  1664. const result = helper.methods.componentsSummaryStatisticsSort();
  1665. let total = 0;
  1666.  
  1667. /* 提供友好的可视化展示方式 */
  1668. console.table && console.table(result.map(item => {
  1669. total += item.componentsSummary.length;
  1670. return {
  1671. componentName: item.componentName,
  1672. count: item.componentsSummary.length
  1673. }
  1674. }));
  1675.  
  1676. debug.log(`${i18n.t('debugHelper.componentsSummaryStatisticsSort')} (total:${total})`, result);
  1677. },
  1678. getDestroyByDuration () {
  1679. const destroyInfo = helper.methods.getDestroyByDuration();
  1680. console.table && console.table(destroyInfo.destroyList);
  1681. debug.log(i18n.t('debugHelper.getDestroyByDuration'), destroyInfo);
  1682. },
  1683. clearAll () {
  1684. helper.methods.clearAll();
  1685. debug.log(i18n.t('debugHelper.clearAll'));
  1686. },
  1687.  
  1688. printLifeCycleInfo () {
  1689. const lifecycleFilters = window.prompt(i18n.t('debugHelper.printLifeCycleInfoPrompt.lifecycleFilters'), helper.config.lifecycle.filters.join(','));
  1690. const componentFilters = window.prompt(i18n.t('debugHelper.printLifeCycleInfoPrompt.componentFilters'), helper.config.lifecycle.componentFilters.join(','));
  1691.  
  1692. if (lifecycleFilters !== null && componentFilters !== null) {
  1693. debug.log(i18n.t('debugHelper.printLifeCycleInfo'));
  1694. helper.methods.printLifeCycleInfo(lifecycleFilters, componentFilters);
  1695. }
  1696. },
  1697.  
  1698. notPrintLifeCycleInfo () {
  1699. debug.log(i18n.t('debugHelper.notPrintLifeCycleInfo'));
  1700. helper.methods.notPrintLifeCycleInfo();
  1701. },
  1702.  
  1703. findComponents () {
  1704. const filters = window.prompt(i18n.t('debugHelper.findComponentsPrompt.filters'), helper.config.findComponentsFilters.join(','));
  1705. if (filters !== null) {
  1706. debug.log(i18n.t('debugHelper.findComponents'), helper.methods.findComponents(filters));
  1707. }
  1708. },
  1709.  
  1710. findNotContainElementComponents () {
  1711. debug.log(i18n.t('debugHelper.findNotContainElementComponents'), helper.methods.findNotContainElementComponents());
  1712. },
  1713.  
  1714. blockComponents () {
  1715. const filters = window.prompt(i18n.t('debugHelper.blockComponentsPrompt.filters'), helper.config.blockFilters.join(','));
  1716. if (filters !== null) {
  1717. helper.methods.blockComponents(filters);
  1718. debug.log(i18n.t('debugHelper.blockComponents'), filters);
  1719. }
  1720. },
  1721.  
  1722. dd () {
  1723. const filter = window.prompt(i18n.t('debugHelper.ddPrompt.filter'), helper.config.dd.filters.join(','));
  1724. const count = window.prompt(i18n.t('debugHelper.ddPrompt.count'), helper.config.dd.count);
  1725.  
  1726. if (filter !== null && count !== null) {
  1727. debug.log(i18n.t('debugHelper.dd'));
  1728. helper.methods.dd(filter, Number(count));
  1729. }
  1730. },
  1731.  
  1732. undd () {
  1733. debug.log(i18n.t('debugHelper.undd'));
  1734. helper.methods.undd();
  1735. },
  1736.  
  1737. toggleHackVueComponent () {
  1738. helper.config.hackVueComponent ? helper.methods.unHackVueComponent() : helper.methods.hackVueComponent();
  1739. helper.config.hackVueComponent = !helper.config.hackVueComponent;
  1740. }
  1741.  
  1742. };
  1743.  
  1744. /*!
  1745. * @name menu.js
  1746. * @description vue-debug-helper的菜单配置
  1747. * @version 0.0.1
  1748. * @author xxxily
  1749. * @date 2022/04/25 22:28
  1750. * @github https://github.com/xxxily
  1751. */
  1752.  
  1753. function menuRegister (Vue) {
  1754. if (!Vue) {
  1755. monkeyMenu.on('not detected ' + i18n.t('issues'), () => {
  1756. window.GM_openInTab('https://github.com/xxxily/vue-debug-helper/issues', {
  1757. active: true,
  1758. insert: true,
  1759. setParent: true
  1760. });
  1761. });
  1762. return false
  1763. }
  1764.  
  1765. /* 批量注册菜单 */
  1766. Object.keys(functionCall).forEach(key => {
  1767. const text = i18n.t(`debugHelper.${key}`);
  1768. if (text && functionCall[key] instanceof Function) {
  1769. monkeyMenu.on(text, functionCall[key]);
  1770. }
  1771. });
  1772.  
  1773. /* 是否开启vue-devtools的菜单 */
  1774. const devtoolsText = helper.config.devtools ? i18n.t('debugHelper.devtools.disable') : i18n.t('debugHelper.devtools.enabled');
  1775. monkeyMenu.on(devtoolsText, helper.methods.toggleDevtools);
  1776.  
  1777. // monkeyMenu.on('i18n.t('setting')', () => {
  1778. // window.alert('功能开发中,敬请期待...')
  1779. // })
  1780.  
  1781. monkeyMenu.on(i18n.t('issues'), () => {
  1782. window.GM_openInTab('https://github.com/xxxily/vue-debug-helper/issues', {
  1783. active: true,
  1784. insert: true,
  1785. setParent: true
  1786. });
  1787. });
  1788.  
  1789. // monkeyMenu.on(i18n.t('donate'), () => {
  1790. // window.GM_openInTab('https://cdn.jsdelivr.net/gh/xxxily/vue-debug-helper@main/donate.png', {
  1791. // active: true,
  1792. // insert: true,
  1793. // setParent: true
  1794. // })
  1795. // })
  1796. }
  1797.  
  1798. const isff = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase().indexOf('firefox') > 0 : false;
  1799.  
  1800. // 绑定事件
  1801. function addEvent (object, event, method) {
  1802. if (object.addEventListener) {
  1803. object.addEventListener(event, method, false);
  1804. } else if (object.attachEvent) {
  1805. object.attachEvent(`on${event}`, () => { method(window.event); });
  1806. }
  1807. }
  1808.  
  1809. // 修饰键转换成对应的键码
  1810. function getMods (modifier, key) {
  1811. const mods = key.slice(0, key.length - 1);
  1812. for (let i = 0; i < mods.length; i++) mods[i] = modifier[mods[i].toLowerCase()];
  1813. return mods
  1814. }
  1815.  
  1816. // 处理传的key字符串转换成数组
  1817. function getKeys (key) {
  1818. if (typeof key !== 'string') key = '';
  1819. key = key.replace(/\s/g, ''); // 匹配任何空白字符,包括空格、制表符、换页符等等
  1820. const keys = key.split(','); // 同时设置多个快捷键,以','分割
  1821. let index = keys.lastIndexOf('');
  1822.  
  1823. // 快捷键可能包含',',需特殊处理
  1824. for (; index >= 0;) {
  1825. keys[index - 1] += ',';
  1826. keys.splice(index, 1);
  1827. index = keys.lastIndexOf('');
  1828. }
  1829.  
  1830. return keys
  1831. }
  1832.  
  1833. // 比较修饰键的数组
  1834. function compareArray (a1, a2) {
  1835. const arr1 = a1.length >= a2.length ? a1 : a2;
  1836. const arr2 = a1.length >= a2.length ? a2 : a1;
  1837. let isIndex = true;
  1838.  
  1839. for (let i = 0; i < arr1.length; i++) {
  1840. if (arr2.indexOf(arr1[i]) === -1) isIndex = false;
  1841. }
  1842. return isIndex
  1843. }
  1844.  
  1845. // Special Keys
  1846. const _keyMap = {
  1847. backspace: 8,
  1848. tab: 9,
  1849. clear: 12,
  1850. enter: 13,
  1851. return: 13,
  1852. esc: 27,
  1853. escape: 27,
  1854. space: 32,
  1855. left: 37,
  1856. up: 38,
  1857. right: 39,
  1858. down: 40,
  1859. del: 46,
  1860. delete: 46,
  1861. ins: 45,
  1862. insert: 45,
  1863. home: 36,
  1864. end: 35,
  1865. pageup: 33,
  1866. pagedown: 34,
  1867. capslock: 20,
  1868. num_0: 96,
  1869. num_1: 97,
  1870. num_2: 98,
  1871. num_3: 99,
  1872. num_4: 100,
  1873. num_5: 101,
  1874. num_6: 102,
  1875. num_7: 103,
  1876. num_8: 104,
  1877. num_9: 105,
  1878. num_multiply: 106,
  1879. num_add: 107,
  1880. num_enter: 108,
  1881. num_subtract: 109,
  1882. num_decimal: 110,
  1883. num_divide: 111,
  1884. '⇪': 20,
  1885. ',': 188,
  1886. '.': 190,
  1887. '/': 191,
  1888. '`': 192,
  1889. '-': isff ? 173 : 189,
  1890. '=': isff ? 61 : 187,
  1891. ';': isff ? 59 : 186,
  1892. '\'': 222,
  1893. '[': 219,
  1894. ']': 221,
  1895. '\\': 220
  1896. };
  1897.  
  1898. // Modifier Keys
  1899. const _modifier = {
  1900. // shiftKey
  1901. '⇧': 16,
  1902. shift: 16,
  1903. // altKey
  1904. '⌥': 18,
  1905. alt: 18,
  1906. option: 18,
  1907. // ctrlKey
  1908. '⌃': 17,
  1909. ctrl: 17,
  1910. control: 17,
  1911. // metaKey
  1912. '⌘': 91,
  1913. cmd: 91,
  1914. command: 91
  1915. };
  1916. const modifierMap = {
  1917. 16: 'shiftKey',
  1918. 18: 'altKey',
  1919. 17: 'ctrlKey',
  1920. 91: 'metaKey',
  1921.  
  1922. shiftKey: 16,
  1923. ctrlKey: 17,
  1924. altKey: 18,
  1925. metaKey: 91
  1926. };
  1927. const _mods = {
  1928. 16: false,
  1929. 18: false,
  1930. 17: false,
  1931. 91: false
  1932. };
  1933. const _handlers = {};
  1934.  
  1935. // F1~F12 special key
  1936. for (let k = 1; k < 20; k++) {
  1937. _keyMap[`f${k}`] = 111 + k;
  1938. }
  1939.  
  1940. // https://github.com/jaywcjlove/hotkeys
  1941.  
  1942. let _downKeys = []; // 记录摁下的绑定键
  1943. let winListendFocus = false; // window是否已经监听了focus事件
  1944. let _scope = 'all'; // 默认热键范围
  1945. const elementHasBindEvent = []; // 已绑定事件的节点记录
  1946.  
  1947. // 返回键码
  1948. const code = (x) => _keyMap[x.toLowerCase()] ||
  1949. _modifier[x.toLowerCase()] ||
  1950. x.toUpperCase().charCodeAt(0);
  1951.  
  1952. // 设置获取当前范围(默认为'所有')
  1953. function setScope (scope) {
  1954. _scope = scope || 'all';
  1955. }
  1956. // 获取当前范围
  1957. function getScope () {
  1958. return _scope || 'all'
  1959. }
  1960. // 获取摁下绑定键的键值
  1961. function getPressedKeyCodes () {
  1962. return _downKeys.slice(0)
  1963. }
  1964.  
  1965. // 表单控件控件判断 返回 Boolean
  1966. // hotkey is effective only when filter return true
  1967. function filter (event) {
  1968. const target = event.target || event.srcElement;
  1969. const { tagName } = target;
  1970. let flag = true;
  1971. // ignore: isContentEditable === 'true', <input> and <textarea> when readOnly state is false, <select>
  1972. if (
  1973. target.isContentEditable ||
  1974. ((tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') && !target.readOnly)
  1975. ) {
  1976. flag = false;
  1977. }
  1978. return flag
  1979. }
  1980.  
  1981. // 判断摁下的键是否为某个键,返回true或者false
  1982. function isPressed (keyCode) {
  1983. if (typeof keyCode === 'string') {
  1984. keyCode = code(keyCode); // 转换成键码
  1985. }
  1986. return _downKeys.indexOf(keyCode) !== -1
  1987. }
  1988.  
  1989. // 循环删除handlers中的所有 scope(范围)
  1990. function deleteScope (scope, newScope) {
  1991. let handlers;
  1992. let i;
  1993.  
  1994. // 没有指定scope,获取scope
  1995. if (!scope) scope = getScope();
  1996.  
  1997. for (const key in _handlers) {
  1998. if (Object.prototype.hasOwnProperty.call(_handlers, key)) {
  1999. handlers = _handlers[key];
  2000. for (i = 0; i < handlers.length;) {
  2001. if (handlers[i].scope === scope) handlers.splice(i, 1);
  2002. else i++;
  2003. }
  2004. }
  2005. }
  2006.  
  2007. // 如果scope被删除,将scope重置为all
  2008. if (getScope() === scope) setScope(newScope || 'all');
  2009. }
  2010.  
  2011. // 清除修饰键
  2012. function clearModifier (event) {
  2013. let key = event.keyCode || event.which || event.charCode;
  2014. const i = _downKeys.indexOf(key);
  2015.  
  2016. // 从列表中清除按压过的键
  2017. if (i >= 0) {
  2018. _downKeys.splice(i, 1);
  2019. }
  2020. // 特殊处理 cmmand 键,在 cmmand 组合快捷键 keyup 只执行一次的问题
  2021. if (event.key && event.key.toLowerCase() === 'meta') {
  2022. _downKeys.splice(0, _downKeys.length);
  2023. }
  2024.  
  2025. // 修饰键 shiftKey altKey ctrlKey (command||metaKey) 清除
  2026. if (key === 93 || key === 224) key = 91;
  2027. if (key in _mods) {
  2028. _mods[key] = false;
  2029.  
  2030. // 将修饰键重置为false
  2031. for (const k in _modifier) if (_modifier[k] === key) hotkeys[k] = false;
  2032. }
  2033. }
  2034.  
  2035. function unbind (keysInfo, ...args) {
  2036. // unbind(), unbind all keys
  2037. if (!keysInfo) {
  2038. Object.keys(_handlers).forEach((key) => delete _handlers[key]);
  2039. } else if (Array.isArray(keysInfo)) {
  2040. // support like : unbind([{key: 'ctrl+a', scope: 's1'}, {key: 'ctrl-a', scope: 's2', splitKey: '-'}])
  2041. keysInfo.forEach((info) => {
  2042. if (info.key) eachUnbind(info);
  2043. });
  2044. } else if (typeof keysInfo === 'object') {
  2045. // support like unbind({key: 'ctrl+a, ctrl+b', scope:'abc'})
  2046. if (keysInfo.key) eachUnbind(keysInfo);
  2047. } else if (typeof keysInfo === 'string') {
  2048. // support old method
  2049. // eslint-disable-line
  2050. let [scope, method] = args;
  2051. if (typeof scope === 'function') {
  2052. method = scope;
  2053. scope = '';
  2054. }
  2055. eachUnbind({
  2056. key: keysInfo,
  2057. scope,
  2058. method,
  2059. splitKey: '+'
  2060. });
  2061. }
  2062. }
  2063.  
  2064. // 解除绑定某个范围的快捷键
  2065. const eachUnbind = ({
  2066. key, scope, method, splitKey = '+'
  2067. }) => {
  2068. const multipleKeys = getKeys(key);
  2069. multipleKeys.forEach((originKey) => {
  2070. const unbindKeys = originKey.split(splitKey);
  2071. const len = unbindKeys.length;
  2072. const lastKey = unbindKeys[len - 1];
  2073. const keyCode = lastKey === '*' ? '*' : code(lastKey);
  2074. if (!_handlers[keyCode]) return
  2075. // 判断是否传入范围,没有就获取范围
  2076. if (!scope) scope = getScope();
  2077. const mods = len > 1 ? getMods(_modifier, unbindKeys) : [];
  2078. _handlers[keyCode] = _handlers[keyCode].filter((record) => {
  2079. // 通过函数判断,是否解除绑定,函数相等直接返回
  2080. const isMatchingMethod = method ? record.method === method : true;
  2081. return !(
  2082. isMatchingMethod &&
  2083. record.scope === scope &&
  2084. compareArray(record.mods, mods)
  2085. )
  2086. });
  2087. });
  2088. };
  2089.  
  2090. // 对监听对应快捷键的回调函数进行处理
  2091. function eventHandler (event, handler, scope, element) {
  2092. if (handler.element !== element) {
  2093. return
  2094. }
  2095. let modifiersMatch;
  2096.  
  2097. // 看它是否在当前范围
  2098. if (handler.scope === scope || handler.scope === 'all') {
  2099. // 检查是否匹配修饰符(如果有返回true)
  2100. modifiersMatch = handler.mods.length > 0;
  2101.  
  2102. for (const y in _mods) {
  2103. if (Object.prototype.hasOwnProperty.call(_mods, y)) {
  2104. if (
  2105. (!_mods[y] && handler.mods.indexOf(+y) > -1) ||
  2106. (_mods[y] && handler.mods.indexOf(+y) === -1)
  2107. ) {
  2108. modifiersMatch = false;
  2109. }
  2110. }
  2111. }
  2112.  
  2113. // 调用处理程序,如果是修饰键不做处理
  2114. if (
  2115. (handler.mods.length === 0 &&
  2116. !_mods[16] &&
  2117. !_mods[18] &&
  2118. !_mods[17] &&
  2119. !_mods[91]) ||
  2120. modifiersMatch ||
  2121. handler.shortcut === '*'
  2122. ) {
  2123. if (handler.method(event, handler) === false) {
  2124. if (event.preventDefault) event.preventDefault();
  2125. else event.returnValue = false;
  2126. if (event.stopPropagation) event.stopPropagation();
  2127. if (event.cancelBubble) event.cancelBubble = true;
  2128. }
  2129. }
  2130. }
  2131. }
  2132.  
  2133. // 处理keydown事件
  2134. function dispatch (event, element) {
  2135. const asterisk = _handlers['*'];
  2136. let key = event.keyCode || event.which || event.charCode;
  2137.  
  2138. // 表单控件过滤 默认表单控件不触发快捷键
  2139. if (!hotkeys.filter.call(this, event)) return
  2140.  
  2141. // Gecko(Firefox)的command键值224,在Webkit(Chrome)中保持一致
  2142. // Webkit左右 command 键值不一样
  2143. if (key === 93 || key === 224) key = 91;
  2144.  
  2145. /**
  2146. * Collect bound keys
  2147. * If an Input Method Editor is processing key input and the event is keydown, return 229.
  2148. * https://stackoverflow.com/questions/25043934/is-it-ok-to-ignore-keydown-events-with-keycode-229
  2149. * http://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
  2150. */
  2151. if (_downKeys.indexOf(key) === -1 && key !== 229) _downKeys.push(key);
  2152. /**
  2153. * Jest test cases are required.
  2154. * ===============================
  2155. */
  2156. ['ctrlKey', 'altKey', 'shiftKey', 'metaKey'].forEach((keyName) => {
  2157. const keyNum = modifierMap[keyName];
  2158. if (event[keyName] && _downKeys.indexOf(keyNum) === -1) {
  2159. _downKeys.push(keyNum);
  2160. } else if (!event[keyName] && _downKeys.indexOf(keyNum) > -1) {
  2161. _downKeys.splice(_downKeys.indexOf(keyNum), 1);
  2162. } else if (keyName === 'metaKey' && event[keyName] && _downKeys.length === 3) {
  2163. /**
  2164. * Fix if Command is pressed:
  2165. * ===============================
  2166. */
  2167. if (!(event.ctrlKey || event.shiftKey || event.altKey)) {
  2168. _downKeys = _downKeys.slice(_downKeys.indexOf(keyNum));
  2169. }
  2170. }
  2171. });
  2172. /**
  2173. * -------------------------------
  2174. */
  2175.  
  2176. if (key in _mods) {
  2177. _mods[key] = true;
  2178.  
  2179. // 将特殊字符的key注册到 hotkeys 上
  2180. for (const k in _modifier) {
  2181. if (_modifier[k] === key) hotkeys[k] = true;
  2182. }
  2183.  
  2184. if (!asterisk) return
  2185. }
  2186.  
  2187. // 将 modifierMap 里面的修饰键绑定到 event 中
  2188. for (const e in _mods) {
  2189. if (Object.prototype.hasOwnProperty.call(_mods, e)) {
  2190. _mods[e] = event[modifierMap[e]];
  2191. }
  2192. }
  2193. /**
  2194. * https://github.com/jaywcjlove/hotkeys/pull/129
  2195. * This solves the issue in Firefox on Windows where hotkeys corresponding to special characters would not trigger.
  2196. * An example of this is ctrl+alt+m on a Swedish keyboard which is used to type μ.
  2197. * Browser support: https://caniuse.com/#feat=keyboardevent-getmodifierstate
  2198. */
  2199. if (event.getModifierState && (!(event.altKey && !event.ctrlKey) && event.getModifierState('AltGraph'))) {
  2200. if (_downKeys.indexOf(17) === -1) {
  2201. _downKeys.push(17);
  2202. }
  2203.  
  2204. if (_downKeys.indexOf(18) === -1) {
  2205. _downKeys.push(18);
  2206. }
  2207.  
  2208. _mods[17] = true;
  2209. _mods[18] = true;
  2210. }
  2211.  
  2212. // 获取范围 默认为 `all`
  2213. const scope = getScope();
  2214. // 对任何快捷键都需要做的处理
  2215. if (asterisk) {
  2216. for (let i = 0; i < asterisk.length; i++) {
  2217. if (
  2218. asterisk[i].scope === scope &&
  2219. ((event.type === 'keydown' && asterisk[i].keydown) ||
  2220. (event.type === 'keyup' && asterisk[i].keyup))
  2221. ) {
  2222. eventHandler(event, asterisk[i], scope, element);
  2223. }
  2224. }
  2225. }
  2226. // key 不在 _handlers 中返回
  2227. if (!(key in _handlers)) return
  2228.  
  2229. for (let i = 0; i < _handlers[key].length; i++) {
  2230. if (
  2231. (event.type === 'keydown' && _handlers[key][i].keydown) ||
  2232. (event.type === 'keyup' && _handlers[key][i].keyup)
  2233. ) {
  2234. if (_handlers[key][i].key) {
  2235. const record = _handlers[key][i];
  2236. const { splitKey } = record;
  2237. const keyShortcut = record.key.split(splitKey);
  2238. const _downKeysCurrent = []; // 记录当前按键键值
  2239. for (let a = 0; a < keyShortcut.length; a++) {
  2240. _downKeysCurrent.push(code(keyShortcut[a]));
  2241. }
  2242. if (_downKeysCurrent.sort().join('') === _downKeys.sort().join('')) {
  2243. // 找到处理内容
  2244. eventHandler(event, record, scope, element);
  2245. }
  2246. }
  2247. }
  2248. }
  2249. }
  2250.  
  2251. // 判断 element 是否已经绑定事件
  2252. function isElementBind (element) {
  2253. return elementHasBindEvent.indexOf(element) > -1
  2254. }
  2255.  
  2256. function hotkeys (key, option, method) {
  2257. _downKeys = [];
  2258. const keys = getKeys(key); // 需要处理的快捷键列表
  2259. let mods = [];
  2260. let scope = 'all'; // scope默认为all,所有范围都有效
  2261. let element = document; // 快捷键事件绑定节点
  2262. let i = 0;
  2263. let keyup = false;
  2264. let keydown = true;
  2265. let splitKey = '+';
  2266.  
  2267. // 对为设定范围的判断
  2268. if (method === undefined && typeof option === 'function') {
  2269. method = option;
  2270. }
  2271.  
  2272. if (Object.prototype.toString.call(option) === '[object Object]') {
  2273. if (option.scope) scope = option.scope; // eslint-disable-line
  2274. if (option.element) element = option.element; // eslint-disable-line
  2275. if (option.keyup) keyup = option.keyup; // eslint-disable-line
  2276. if (option.keydown !== undefined) keydown = option.keydown; // eslint-disable-line
  2277. if (typeof option.splitKey === 'string') splitKey = option.splitKey; // eslint-disable-line
  2278. }
  2279.  
  2280. if (typeof option === 'string') scope = option;
  2281.  
  2282. // 对于每个快捷键进行处理
  2283. for (; i < keys.length; i++) {
  2284. key = keys[i].split(splitKey); // 按键列表
  2285. mods = [];
  2286.  
  2287. // 如果是组合快捷键取得组合快捷键
  2288. if (key.length > 1) mods = getMods(_modifier, key);
  2289.  
  2290. // 将非修饰键转化为键码
  2291. key = key[key.length - 1];
  2292. key = key === '*' ? '*' : code(key); // *表示匹配所有快捷键
  2293.  
  2294. // 判断key是否在_handlers中,不在就赋一个空数组
  2295. if (!(key in _handlers)) _handlers[key] = [];
  2296. _handlers[key].push({
  2297. keyup,
  2298. keydown,
  2299. scope,
  2300. mods,
  2301. shortcut: keys[i],
  2302. method,
  2303. key: keys[i],
  2304. splitKey,
  2305. element
  2306. });
  2307. }
  2308. // 在全局document上设置快捷键
  2309. if (typeof element !== 'undefined' && !isElementBind(element) && window) {
  2310. elementHasBindEvent.push(element);
  2311. addEvent(element, 'keydown', (e) => {
  2312. dispatch(e, element);
  2313. });
  2314. if (!winListendFocus) {
  2315. winListendFocus = true;
  2316. addEvent(window, 'focus', () => {
  2317. _downKeys = [];
  2318. });
  2319. }
  2320. addEvent(element, 'keyup', (e) => {
  2321. dispatch(e, element);
  2322. clearModifier(e);
  2323. });
  2324. }
  2325. }
  2326.  
  2327. function trigger (shortcut, scope = 'all') {
  2328. Object.keys(_handlers).forEach((key) => {
  2329. const data = _handlers[key].find((item) => item.scope === scope && item.shortcut === shortcut);
  2330. if (data && data.method) {
  2331. data.method();
  2332. }
  2333. });
  2334. }
  2335.  
  2336. const _api = {
  2337. setScope,
  2338. getScope,
  2339. deleteScope,
  2340. getPressedKeyCodes,
  2341. isPressed,
  2342. filter,
  2343. trigger,
  2344. unbind,
  2345. keyMap: _keyMap,
  2346. modifier: _modifier,
  2347. modifierMap
  2348. };
  2349. for (const a in _api) {
  2350. if (Object.prototype.hasOwnProperty.call(_api, a)) {
  2351. hotkeys[a] = _api[a];
  2352. }
  2353. }
  2354.  
  2355. if (typeof window !== 'undefined') {
  2356. const _hotkeys = window.hotkeys;
  2357. hotkeys.noConflict = (deep) => {
  2358. if (deep && window.hotkeys === hotkeys) {
  2359. window.hotkeys = _hotkeys;
  2360. }
  2361. return hotkeys
  2362. };
  2363. window.hotkeys = hotkeys;
  2364. }
  2365.  
  2366. /*!
  2367. * @name hotKeyRegister.js
  2368. * @description vue-debug-helper的快捷键配置
  2369. * @version 0.0.1
  2370. * @author xxxily
  2371. * @date 2022/04/26 14:37
  2372. * @github https://github.com/xxxily
  2373. */
  2374.  
  2375. function hotKeyRegister () {
  2376. const hotKeyMap = {
  2377. 'shift+alt+a,shift+alt+ctrl+a': functionCall.componentsSummaryStatisticsSort,
  2378. 'shift+alt+l': functionCall.componentsStatistics,
  2379. 'shift+alt+d': functionCall.destroyStatisticsSort,
  2380. 'shift+alt+c': functionCall.clearAll,
  2381. 'shift+alt+e': function (event, handler) {
  2382. if (helper.config.dd.enabled) {
  2383. functionCall.undd();
  2384. } else {
  2385. functionCall.dd();
  2386. }
  2387. }
  2388. };
  2389.  
  2390. Object.keys(hotKeyMap).forEach(key => {
  2391. hotkeys(key, hotKeyMap[key]);
  2392. });
  2393. }
  2394.  
  2395. /*!
  2396. * @name vueDetector.js
  2397. * @description 检测页面是否存在Vue对象
  2398. * @version 0.0.1
  2399. * @author xxxily
  2400. * @date 2022/04/27 11:43
  2401. * @github https://github.com/xxxily
  2402. */
  2403.  
  2404. function mutationDetector (callback, shadowRoot) {
  2405. const win = window;
  2406. const MutationObserver = win.MutationObserver || win.WebKitMutationObserver;
  2407. const docRoot = shadowRoot || win.document.documentElement;
  2408. const maxDetectTries = 1500;
  2409. const timeout = 1000 * 10;
  2410. const startTime = Date.now();
  2411. let detectCount = 0;
  2412. let detectStatus = false;
  2413.  
  2414. if (!MutationObserver) {
  2415. debug.warn('MutationObserver is not supported in this browser');
  2416. return false
  2417. }
  2418.  
  2419. let mObserver = null;
  2420. const mObserverCallback = (mutationsList, observer) => {
  2421. if (detectStatus) {
  2422. return
  2423. }
  2424.  
  2425. /* 超时或检测次数过多,取消监听 */
  2426. if (Date.now() - startTime > timeout || detectCount > maxDetectTries) {
  2427. debug.warn('mutationDetector timeout or detectCount > maxDetectTries, stop detect');
  2428. if (mObserver && mObserver.disconnect) {
  2429. mObserver.disconnect();
  2430. mObserver = null;
  2431. }
  2432. }
  2433.  
  2434. for (let i = 0; i < mutationsList.length; i++) {
  2435. detectCount++;
  2436. const mutation = mutationsList[i];
  2437. if (mutation.target && mutation.target.__vue__) {
  2438. let Vue = Object.getPrototypeOf(mutation.target.__vue__).constructor;
  2439. while (Vue.super) {
  2440. Vue = Vue.super;
  2441. }
  2442.  
  2443. /* 检测成功后销毁观察对象 */
  2444. if (mObserver && mObserver.disconnect) {
  2445. mObserver.disconnect();
  2446. mObserver = null;
  2447. }
  2448.  
  2449. detectStatus = true;
  2450. callback && callback(Vue);
  2451. break
  2452. }
  2453. }
  2454. };
  2455.  
  2456. mObserver = new MutationObserver(mObserverCallback);
  2457. mObserver.observe(docRoot, {
  2458. attributes: true,
  2459. childList: true,
  2460. subtree: true
  2461. });
  2462. }
  2463.  
  2464. /**
  2465. * 检测页面是否存在Vue对象,方法参考:https://github.com/vuejs/devtools/blob/main/packages/shell-chrome/src/detector.js
  2466. * @param {window} win windwod对象
  2467. * @param {function} callback 检测到Vue对象后的回调函数
  2468. */
  2469. function vueDetect (win, callback) {
  2470. let delay = 1000;
  2471. let detectRemainingTries = 10;
  2472. let detectSuc = false;
  2473.  
  2474. // Method 1: MutationObserver detector
  2475. mutationDetector((Vue) => {
  2476. if (!detectSuc) {
  2477. debug.info(`------------- Vue mutation detected (${Vue.version}) -------------`);
  2478. detectSuc = true;
  2479. callback(Vue);
  2480. }
  2481. });
  2482.  
  2483. function runDetect () {
  2484. if (detectSuc) {
  2485. return false
  2486. }
  2487.  
  2488. // Method 2: Check Vue 3
  2489. const vueDetected = !!(win.__VUE__);
  2490. if (vueDetected) {
  2491. debug.info(`------------- Vue global detected (${win.__VUE__.version}) -------------`);
  2492. detectSuc = true;
  2493. callback(win.__VUE__);
  2494. return
  2495. }
  2496.  
  2497. // Method 3: Scan all elements inside document
  2498. const all = document.querySelectorAll('*');
  2499. let el;
  2500. for (let i = 0; i < all.length; i++) {
  2501. if (all[i].__vue__) {
  2502. el = all[i];
  2503. break
  2504. }
  2505. }
  2506. if (el) {
  2507. let Vue = Object.getPrototypeOf(el.__vue__).constructor;
  2508. while (Vue.super) {
  2509. Vue = Vue.super;
  2510. }
  2511. debug.info(`------------- Vue dom detected (${Vue.version}) -------------`);
  2512. detectSuc = true;
  2513. callback(Vue);
  2514. return
  2515. }
  2516.  
  2517. if (detectRemainingTries > 0) {
  2518. detectRemainingTries--;
  2519.  
  2520. if (detectRemainingTries >= 7) {
  2521. setTimeout(() => {
  2522. runDetect();
  2523. }, 40);
  2524. } else {
  2525. setTimeout(() => {
  2526. runDetect();
  2527. }, delay);
  2528. delay *= 5;
  2529. }
  2530. }
  2531. }
  2532.  
  2533. setTimeout(() => {
  2534. runDetect();
  2535. }, 40);
  2536. }
  2537.  
  2538. /**
  2539. * 判断是否处于Iframe中
  2540. * @returns {boolean}
  2541. */
  2542. function isInIframe () {
  2543. return window !== window.top
  2544. }
  2545.  
  2546. /**
  2547. * 由于tampermonkey对window对象进行了封装,我们实际访问到的window并非页面真实的window
  2548. * 这就导致了如果我们需要将某些对象挂载到页面的window进行调试的时候就无法挂载了
  2549. * 所以必须使用特殊手段才能访问到页面真实的window对象,于是就有了下面这个函数
  2550. * @returns {Promise<void>}
  2551. */
  2552. async function getPageWindow () {
  2553. return new Promise(function (resolve, reject) {
  2554. if (window._pageWindow) {
  2555. return resolve(window._pageWindow)
  2556. }
  2557.  
  2558. const listenEventList = ['load', 'mousemove', 'scroll', 'get-page-window-event'];
  2559.  
  2560. function getWin (event) {
  2561. window._pageWindow = this;
  2562. // debug.log('getPageWindow succeed', event)
  2563. listenEventList.forEach(eventType => {
  2564. window.removeEventListener(eventType, getWin, true);
  2565. });
  2566. resolve(window._pageWindow);
  2567. }
  2568.  
  2569. listenEventList.forEach(eventType => {
  2570. window.addEventListener(eventType, getWin, true);
  2571. });
  2572.  
  2573. /* 自行派发事件以便用最短的时候获得pageWindow对象 */
  2574. window.dispatchEvent(new window.Event('get-page-window-event'));
  2575. })
  2576. }
  2577. // getPageWindow()
  2578.  
  2579. /**
  2580. * 通过同步的方式获取pageWindow
  2581. * 注意同步获取的方式需要将脚本写入head,部分网站由于安全策略会导致写入失败,而无法正常获取
  2582. * @returns {*}
  2583. */
  2584. function getPageWindowSync () {
  2585. if (document._win_) return document._win_
  2586.  
  2587. const head = document.head || document.querySelector('head');
  2588. const script = document.createElement('script');
  2589. script.appendChild(document.createTextNode('document._win_ = window'));
  2590. head.appendChild(script);
  2591.  
  2592. return document._win_
  2593. }
  2594.  
  2595. let registerStatus = 'init';
  2596. window._debugMode_ = true;
  2597.  
  2598. function init (win) {
  2599. if (isInIframe()) {
  2600. debug.log('running in iframe, skip init', window.location.href);
  2601. return false
  2602. }
  2603.  
  2604. if (registerStatus === 'initing') {
  2605. return false
  2606. }
  2607.  
  2608. registerStatus = 'initing';
  2609.  
  2610. vueDetect(win, function (Vue) {
  2611. /* 挂载到window上,方便通过控制台调用调试 */
  2612. helper.Vue = Vue;
  2613. win.vueDebugHelper = helper;
  2614.  
  2615. mixinRegister(Vue);
  2616. menuRegister(Vue);
  2617. hotKeyRegister();
  2618.  
  2619. debug.log('vue debug helper register success');
  2620. registerStatus = 'success';
  2621. });
  2622.  
  2623. setTimeout(() => {
  2624. if (registerStatus !== 'success') {
  2625. menuRegister(null);
  2626. debug.warn('vue debug helper register failed, please check if vue is loaded .', win.location.href);
  2627. }
  2628. }, 1000 * 10);
  2629. }
  2630.  
  2631. let win$1 = null;
  2632. try {
  2633. win$1 = getPageWindowSync();
  2634. if (win$1) {
  2635. init(win$1);
  2636. debug.log('getPageWindowSync success');
  2637. }
  2638. } catch (e) {
  2639. debug.error('getPageWindowSync failed', e);
  2640. }
  2641. (async function () {
  2642. if (!win$1) {
  2643. win$1 = await getPageWindow();
  2644. init(win$1);
  2645. }
  2646. })();