index.js 2.1 KB

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