chromeExtension.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. const { app, session } = require('electron');
  3. const _ = require('lodash');
  4. const fs = require('fs');
  5. const path = require('path');
  6. /**
  7. * chrome扩展模块
  8. */
  9. module.exports = {
  10. /**
  11. * 安装
  12. */
  13. install (eeApp) {
  14. console.log('[preload] load chrome extension module');
  15. const extensionIds = this.getAllIds();
  16. for (let i = 0; i < extensionIds.length; i++) {
  17. await this.load(extensionIds[i]);
  18. }
  19. },
  20. /**
  21. * 获取扩展id列表(crx解压后的目录名,即是该扩展的id)
  22. */
  23. getAllIds () {
  24. const extendsionDir = this.getDirectory();
  25. const ids = getDirs(extendsionDir);
  26. return ids;
  27. },
  28. /**
  29. * 扩展所在目录
  30. */
  31. getDirectory () {
  32. let extensionDirPath = '';
  33. let variablePath = 'build'; // 打包前路径
  34. if (app.isPackaged) {
  35. variablePath = '..'; // 打包后路径
  36. }
  37. extensionDirPath = path.join(app.getAppPath(), variablePath, "extraResources", "chromeExtension");
  38. return extensionDirPath;
  39. },
  40. /**
  41. * 加载扩展
  42. */
  43. load (extensionId = '') {
  44. if (_.isEmpty(extensionId)) {
  45. return false
  46. }
  47. try {
  48. const extensionPath = path.join(this.getDirectory(), extensionId);
  49. console.log('[chromeExtension] [load] extensionPath:', extensionPath);
  50. await session.defaultSession.loadExtension(extensionPath, { allowFileAccess: true });
  51. } catch (e) {
  52. console.log('[chromeExtension] [load] load extension error extensionId:%s, errorInfo:%s', extensionId, e.toString());
  53. return false
  54. }
  55. return true
  56. }
  57. }
  58. /**
  59. * 获取目录下所有文件夹
  60. */
  61. function getDirs(dir) {
  62. if (!dir) {
  63. return [];
  64. }
  65. const components = [];
  66. const files = fs.readdirSync(dir);
  67. files.forEach(function(item, index) {
  68. const stat = fs.lstatSync(dir + '/' + item);
  69. if (stat.isDirectory() === true) {
  70. components.push(item);
  71. }
  72. });
  73. return components;
  74. };