index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const { app, session } = require('electron');
  2. const _ = require('lodash');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const Log = require('ee-core/log');
  6. /**
  7. * 扩展插件 (electron自身对该功能并不完全支持,官方也不建议使用)
  8. * @class
  9. */
  10. class ChromeExtensionAddon {
  11. constructor() {
  12. }
  13. /**
  14. * 创建
  15. */
  16. async create () {
  17. Log.info('[addon:chromeExtension] load');
  18. const extensionIds = this.getAllIds();
  19. for (let i = 0; i < extensionIds.length; i++) {
  20. await this.load(extensionIds[i]);
  21. }
  22. }
  23. /**
  24. * 获取扩展id列表(crx解压后的目录名,即是该扩展的id)
  25. */
  26. getAllIds () {
  27. const extendsionDir = this.getDirectory();
  28. const ids = this.getDirs(extendsionDir);
  29. return ids;
  30. }
  31. /**
  32. * 扩展所在目录
  33. */
  34. getDirectory () {
  35. let extensionDirPath = '';
  36. let variablePath = 'build'; // 打包前路径
  37. if (app.isPackaged) {
  38. variablePath = '..'; // 打包后路径
  39. }
  40. extensionDirPath = path.join(app.getAppPath(), variablePath, "extraResources", "chromeExtension");
  41. return extensionDirPath;
  42. }
  43. /**
  44. * 加载扩展
  45. */
  46. async load (extensionId = '') {
  47. if (_.isEmpty(extensionId)) {
  48. return false
  49. }
  50. try {
  51. const extensionPath = path.join(this.getDirectory(), extensionId);
  52. Log.info('[addon:chromeExtension] extensionPath:', extensionPath);
  53. await session.defaultSession.loadExtension(extensionPath, { allowFileAccess: true });
  54. } catch (e) {
  55. Log.info('[addon:chromeExtension] load extension error extensionId:%s, errorInfo:%s', extensionId, e.toString());
  56. return false
  57. }
  58. return true
  59. }
  60. /**
  61. * 获取目录下所有文件夹
  62. */
  63. getDirs(dir) {
  64. if (!dir) {
  65. return [];
  66. }
  67. const components = [];
  68. const files = fs.readdirSync(dir);
  69. files.forEach(function(item, index) {
  70. const stat = fs.lstatSync(dir + '/' + item);
  71. if (stat.isDirectory() === true) {
  72. components.push(item);
  73. }
  74. });
  75. return components;
  76. };
  77. }
  78. ChromeExtensionAddon.toString = () => '[class ChromeExtensionAddon]';
  79. module.exports = ChromeExtensionAddon;