init.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. // The global variable will be used by ipc for event dispatching
  34. const v8Util = process._linkedBinding('electron_common_v8_util');
  35. const { ipcRendererInternal } = require('@electron/internal/renderer/ipc-renderer-internal') as typeof ipcRendererInternalModule;
  36. const ipcRenderer = require('@electron/internal/renderer/api/ipc-renderer').default;
  37. v8Util.setHiddenValue(global, 'ipcNative', {
  38. onMessage (internal: boolean, channel: string, ports: any[], args: any[], senderId: number) {
  39. const sender = internal ? ipcRendererInternal : ipcRenderer;
  40. sender.emit(channel, { sender, senderId, ports }, ...args);
  41. }
  42. });
  43. process.getProcessMemoryInfo = () => {
  44. return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO);
  45. };
  46. // Use electron module after everything is ready.
  47. const { webFrameInit } = require('@electron/internal/renderer/web-frame-init');
  48. webFrameInit();
  49. // Process command line arguments.
  50. const { hasSwitch, getSwitchValue } = process._linkedBinding('electron_common_command_line');
  51. const { getWebPreference } = process._linkedBinding('electron_renderer_web_frame');
  52. const parseOption = function<TDefault> (
  53. name: string, defaultValue: TDefault, converter?: (value: string) => any
  54. ) {
  55. const value = getWebPreference(window, name);
  56. return value
  57. ? (
  58. converter
  59. ? converter(value)
  60. : value
  61. )
  62. : defaultValue;
  63. };
  64. const contextIsolation = getWebPreference(window, 'contextIsolation');
  65. const nodeIntegration = getWebPreference(window, 'nodeIntegration');
  66. const webviewTag = getWebPreference(window, 'webviewTag');
  67. const isHiddenPage = getWebPreference(window, 'hiddenPage');
  68. const usesNativeWindowOpen = getWebPreference(window, 'nativeWindowOpen');
  69. const rendererProcessReuseEnabled = getWebPreference(window, 'disableElectronSiteInstanceOverrides');
  70. const preloadScript = parseOption('preload', null);
  71. const preloadScripts = parseOption('preloadScripts', []);
  72. const guestInstanceId = parseOption('guestInstanceId', null, value => parseInt(value));
  73. const openerId = parseOption('openerId', null, value => parseInt(value));
  74. const appPath = hasSwitch('app-path') ? getSwitchValue('app-path') : null;
  75. // The webContents preload script is loaded after the session preload scripts.
  76. if (preloadScript) {
  77. preloadScripts.push(preloadScript);
  78. }
  79. switch (window.location.protocol) {
  80. case 'devtools:': {
  81. // Override some inspector APIs.
  82. require('@electron/internal/renderer/inspector');
  83. break;
  84. }
  85. case 'chrome-extension:': {
  86. break;
  87. }
  88. case 'chrome:':
  89. break;
  90. default: {
  91. // Override default web functions.
  92. const { windowSetup } = require('@electron/internal/renderer/window-setup');
  93. windowSetup(guestInstanceId, openerId, isHiddenPage, usesNativeWindowOpen, rendererProcessReuseEnabled);
  94. }
  95. }
  96. // Load webview tag implementation.
  97. if (process.isMainFrame) {
  98. const { webViewInit } = require('@electron/internal/renderer/web-view/web-view-init');
  99. webViewInit(contextIsolation, webviewTag, guestInstanceId);
  100. }
  101. if (nodeIntegration) {
  102. // Export node bindings to global.
  103. const { makeRequireFunction } = __non_webpack_require__('internal/modules/cjs/helpers') // eslint-disable-line
  104. global.module = new Module('electron/js2c/renderer_init');
  105. global.require = makeRequireFunction(global.module);
  106. // Set the __filename to the path of html file if it is file: protocol.
  107. if (window.location.protocol === 'file:') {
  108. const location = window.location;
  109. let pathname = location.pathname;
  110. if (process.platform === 'win32') {
  111. if (pathname[0] === '/') pathname = pathname.substr(1);
  112. const isWindowsNetworkSharePath = location.hostname.length > 0 && process.resourcesPath.startsWith('\\');
  113. if (isWindowsNetworkSharePath) {
  114. pathname = `//${location.host}/${pathname}`;
  115. }
  116. }
  117. global.__filename = path.normalize(decodeURIComponent(pathname));
  118. global.__dirname = path.dirname(global.__filename);
  119. // Set module's filename so relative require can work as expected.
  120. global.module.filename = global.__filename;
  121. // Also search for module under the html file.
  122. global.module.paths = Module._nodeModulePaths(global.__dirname);
  123. } else {
  124. // For backwards compatibility we fake these two paths here
  125. global.__filename = path.join(process.resourcesPath, 'electron.asar', 'renderer', 'init.js');
  126. global.__dirname = path.join(process.resourcesPath, 'electron.asar', 'renderer');
  127. if (appPath) {
  128. // Search for module under the app directory
  129. global.module.paths = Module._nodeModulePaths(appPath);
  130. }
  131. }
  132. // Redirect window.onerror to uncaughtException.
  133. window.onerror = function (_message, _filename, _lineno, _colno, error) {
  134. if (global.process.listenerCount('uncaughtException') > 0) {
  135. // We do not want to add `uncaughtException` to our definitions
  136. // because we don't want anyone else (anywhere) to throw that kind
  137. // of error.
  138. global.process.emit('uncaughtException' as any, error as any);
  139. return true;
  140. } else {
  141. return false;
  142. }
  143. };
  144. } else {
  145. // Delete Node's symbols after the Environment has been loaded in a
  146. // non context-isolated environment
  147. if (!contextIsolation) {
  148. process.once('loaded', function () {
  149. delete (global as any).process;
  150. delete (global as any).Buffer;
  151. delete (global as any).setImmediate;
  152. delete (global as any).clearImmediate;
  153. delete (global as any).global;
  154. delete (global as any).root;
  155. delete (global as any).GLOBAL;
  156. });
  157. }
  158. }
  159. // Load the preload scripts.
  160. for (const preloadScript of preloadScripts) {
  161. try {
  162. Module._load(preloadScript);
  163. } catch (error) {
  164. console.error(`Unable to load preload script: ${preloadScript}`);
  165. console.error(error);
  166. ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadScript, error);
  167. }
  168. }
  169. // Warn about security issues
  170. if (process.isMainFrame) {
  171. const { securityWarnings } = require('@electron/internal/renderer/security-warnings');
  172. securityWarnings(nodeIntegration);
  173. }