init.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import * as path from 'path';
  2. import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
  3. import type * as ipcRendererInternalModule from '@electron/internal/renderer/ipc-renderer-internal';
  4. const Module = require('module');
  5. // Make sure globals like "process" and "global" are always available in preload
  6. // scripts even after they are deleted in "loaded" script.
  7. //
  8. // Note 1: We rely on a Node patch to actually pass "process" and "global" and
  9. // other arguments to the wrapper.
  10. //
  11. // Note 2: Node introduced a new code path to use native code to wrap module
  12. // code, which does not work with this hack. However by modifying the
  13. // "Module.wrapper" we can force Node to use the old code path to wrap module
  14. // code with JavaScript.
  15. //
  16. // Note 3: We provide the equivalent extra variables internally through the
  17. // webpack ProvidePlugin in webpack.config.base.js. If you add any extra
  18. // variables to this wrapper please ensure to update that plugin as well.
  19. Module.wrapper = [
  20. '(function (exports, require, module, __filename, __dirname, process, global, Buffer) { ' +
  21. // By running the code in a new closure, it would be possible for the module
  22. // code to override "process" and "Buffer" with local variables.
  23. 'return function (exports, require, module, __filename, __dirname) { ',
  24. '\n}.call(this, exports, require, module, __filename, __dirname); });'
  25. ];
  26. // We modified the original process.argv to let node.js load the
  27. // init.js, we need to restore it here.
  28. process.argv.splice(1, 1);
  29. // Clear search paths.
  30. require('../common/reset-search-paths');
  31. // Import common settings.
  32. require('@electron/internal/common/init');
  33. const { ipcRendererInternal } = require('@electron/internal/renderer/ipc-renderer-internal') as typeof ipcRendererInternalModule;
  34. process.getProcessMemoryInfo = () => {
  35. return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO);
  36. };
  37. // Process command line arguments.
  38. const { hasSwitch, getSwitchValue } = process._linkedBinding('electron_common_command_line');
  39. const { mainFrame } = process._linkedBinding('electron_renderer_web_frame');
  40. const nodeIntegration = mainFrame.getWebPreference('nodeIntegration');
  41. const preloadScript = mainFrame.getWebPreference('preload');
  42. const preloadScripts = mainFrame.getWebPreference('preloadScripts');
  43. const appPath = hasSwitch('app-path') ? getSwitchValue('app-path') : null;
  44. // The webContents preload script is loaded after the session preload scripts.
  45. if (preloadScript) {
  46. preloadScripts.push(preloadScript);
  47. }
  48. // Common renderer initialization
  49. require('@electron/internal/renderer/common-init');
  50. if (nodeIntegration) {
  51. // Export node bindings to global.
  52. const { makeRequireFunction } = __non_webpack_require__('internal/modules/cjs/helpers') // eslint-disable-line
  53. global.module = new Module('electron/js2c/renderer_init');
  54. global.require = makeRequireFunction(global.module);
  55. // Set the __filename to the path of html file if it is file: protocol.
  56. if (window.location.protocol === 'file:') {
  57. const location = window.location;
  58. let pathname = location.pathname;
  59. if (process.platform === 'win32') {
  60. if (pathname[0] === '/') pathname = pathname.substr(1);
  61. const isWindowsNetworkSharePath = location.hostname.length > 0 && process.resourcesPath.startsWith('\\');
  62. if (isWindowsNetworkSharePath) {
  63. pathname = `//${location.host}/${pathname}`;
  64. }
  65. }
  66. global.__filename = path.normalize(decodeURIComponent(pathname));
  67. global.__dirname = path.dirname(global.__filename);
  68. // Set module's filename so relative require can work as expected.
  69. global.module.filename = global.__filename;
  70. // Also search for module under the html file.
  71. global.module.paths = Module._nodeModulePaths(global.__dirname);
  72. } else {
  73. // For backwards compatibility we fake these two paths here
  74. global.__filename = path.join(process.resourcesPath, 'electron.asar', 'renderer', 'init.js');
  75. global.__dirname = path.join(process.resourcesPath, 'electron.asar', 'renderer');
  76. if (appPath) {
  77. // Search for module under the app directory
  78. global.module.paths = Module._nodeModulePaths(appPath);
  79. }
  80. }
  81. // Redirect window.onerror to uncaughtException.
  82. window.onerror = function (_message, _filename, _lineno, _colno, error) {
  83. if (global.process.listenerCount('uncaughtException') > 0) {
  84. // We do not want to add `uncaughtException` to our definitions
  85. // because we don't want anyone else (anywhere) to throw that kind
  86. // of error.
  87. global.process.emit('uncaughtException', error as any);
  88. return true;
  89. } else {
  90. return false;
  91. }
  92. };
  93. } else {
  94. // Delete Node's symbols after the Environment has been loaded in a
  95. // non context-isolated environment
  96. if (!process.contextIsolated) {
  97. process.once('loaded', function () {
  98. delete (global as any).process;
  99. delete (global as any).Buffer;
  100. delete (global as any).setImmediate;
  101. delete (global as any).clearImmediate;
  102. delete (global as any).global;
  103. delete (global as any).root;
  104. delete (global as any).GLOBAL;
  105. });
  106. }
  107. }
  108. // Load the preload scripts.
  109. for (const preloadScript of preloadScripts) {
  110. try {
  111. Module._load(preloadScript);
  112. } catch (error) {
  113. console.error(`Unable to load preload script: ${preloadScript}`);
  114. console.error(error);
  115. ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadScript, error);
  116. }
  117. }