chromeExtension.js 1.9 KB

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