init.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import { EventEmitter } from 'events';
  2. import * as path from 'path';
  3. const Module = require('module');
  4. // Make sure globals like "process" and "global" are always available in preload
  5. // scripts even after they are deleted in "loaded" script.
  6. //
  7. // Note 1: We rely on a Node patch to actually pass "process" and "global" and
  8. // other arguments to the wrapper.
  9. //
  10. // Note 2: Node introduced a new code path to use native code to wrap module
  11. // code, which does not work with this hack. However by modifying the
  12. // "Module.wrapper" we can force Node to use the old code path to wrap module
  13. // code with JavaScript.
  14. //
  15. // Note 3: We provide the equivalent extra variables internally through the
  16. // webpack ProvidePlugin in webpack.config.base.js. If you add any extra
  17. // variables to this wrapper please ensure to update that plugin as well.
  18. Module.wrapper = [
  19. '(function (exports, require, module, __filename, __dirname, process, global, Buffer) { ' +
  20. // By running the code in a new closure, it would be possible for the module
  21. // code to override "process" and "Buffer" with local variables.
  22. 'return function (exports, require, module, __filename, __dirname) { ',
  23. '\n}.call(this, exports, require, module, __filename, __dirname); });'
  24. ];
  25. // We modified the original process.argv to let node.js load the
  26. // init.js, we need to restore it here.
  27. process.argv.splice(1, 1);
  28. // Clear search paths.
  29. require('../common/reset-search-paths');
  30. // Import common settings.
  31. require('@electron/internal/common/init');
  32. // The global variable will be used by ipc for event dispatching
  33. const v8Util = process.electronBinding('v8_util');
  34. const ipcEmitter = new EventEmitter();
  35. const ipcInternalEmitter = new EventEmitter();
  36. v8Util.setHiddenValue(global, 'ipc', ipcEmitter);
  37. v8Util.setHiddenValue(global, 'ipc-internal', ipcInternalEmitter);
  38. v8Util.setHiddenValue(global, 'ipcNative', {
  39. onMessage (internal: boolean, channel: string, args: any[], senderId: number) {
  40. const sender = internal ? ipcInternalEmitter : ipcEmitter;
  41. sender.emit(channel, { sender, senderId }, ...args);
  42. }
  43. });
  44. // Use electron module after everything is ready.
  45. const { ipcRendererInternal } = require('@electron/internal/renderer/ipc-renderer-internal');
  46. const ipcRendererUtils = require('@electron/internal/renderer/ipc-renderer-internal-utils');
  47. const { webFrameInit } = require('@electron/internal/renderer/web-frame-init');
  48. webFrameInit();
  49. // Process command line arguments.
  50. const { hasSwitch, getSwitchValue } = process.electronBinding('command_line');
  51. const parseOption = function<T> (
  52. name: string, defaultValue: T, converter?: (value: string) => T
  53. ) {
  54. return hasSwitch(name)
  55. ? (
  56. converter
  57. ? converter(getSwitchValue(name))
  58. : getSwitchValue(name)
  59. )
  60. : defaultValue;
  61. };
  62. const contextIsolation = hasSwitch('context-isolation');
  63. const nodeIntegration = hasSwitch('node-integration');
  64. const webviewTag = hasSwitch('webview-tag');
  65. const isHiddenPage = hasSwitch('hidden-page');
  66. const usesNativeWindowOpen = hasSwitch('native-window-open');
  67. const preloadScript = parseOption('preload', null);
  68. const preloadScripts = parseOption('preload-scripts', [], value => value.split(path.delimiter)) as string[];
  69. const appPath = parseOption('app-path', null);
  70. const guestInstanceId = parseOption('guest-instance-id', null, value => parseInt(value));
  71. const openerId = parseOption('opener-id', null, value => parseInt(value));
  72. // The arguments to be passed to isolated world.
  73. const isolatedWorldArgs = { ipcRendererInternal, guestInstanceId, isHiddenPage, openerId, usesNativeWindowOpen };
  74. // The webContents preload script is loaded after the session preload scripts.
  75. if (preloadScript) {
  76. preloadScripts.push(preloadScript);
  77. }
  78. switch (window.location.protocol) {
  79. case 'devtools:': {
  80. // Override some inspector APIs.
  81. require('@electron/internal/renderer/inspector');
  82. break;
  83. }
  84. case 'chrome-extension:': {
  85. // Inject the chrome.* APIs that chrome extensions require
  86. require('@electron/internal/renderer/chrome-api').injectTo(window.location.hostname, window);
  87. break;
  88. }
  89. case 'chrome:':
  90. break;
  91. default: {
  92. // Override default web functions.
  93. const { windowSetup } = require('@electron/internal/renderer/window-setup');
  94. windowSetup(guestInstanceId, openerId, isHiddenPage, usesNativeWindowOpen);
  95. // Inject content scripts.
  96. const contentScripts = ipcRendererUtils.invokeSync('ELECTRON_GET_CONTENT_SCRIPTS') as Electron.ContentScriptEntry[];
  97. require('@electron/internal/renderer/content-scripts-injector')(contentScripts);
  98. }
  99. }
  100. // Load webview tag implementation.
  101. if (process.isMainFrame) {
  102. const { webViewInit } = require('@electron/internal/renderer/web-view/web-view-init');
  103. webViewInit(contextIsolation, webviewTag, guestInstanceId);
  104. }
  105. // Pass the arguments to isolatedWorld.
  106. if (contextIsolation) {
  107. v8Util.setHiddenValue(global, 'isolated-world-args', isolatedWorldArgs);
  108. }
  109. if (nodeIntegration) {
  110. // Export node bindings to global.
  111. const { makeRequireFunction } = __non_webpack_require__('internal/modules/cjs/helpers') // eslint-disable-line
  112. global.module = new Module('electron/js2c/renderer_init');
  113. global.require = makeRequireFunction(global.module);
  114. // Set the __filename to the path of html file if it is file: protocol.
  115. if (window.location.protocol === 'file:') {
  116. const location = window.location;
  117. let pathname = location.pathname;
  118. if (process.platform === 'win32') {
  119. if (pathname[0] === '/') pathname = pathname.substr(1);
  120. const isWindowsNetworkSharePath = location.hostname.length > 0 && process.resourcesPath.startsWith('\\');
  121. if (isWindowsNetworkSharePath) {
  122. pathname = `//${location.host}/${pathname}`;
  123. }
  124. }
  125. global.__filename = path.normalize(decodeURIComponent(pathname));
  126. global.__dirname = path.dirname(global.__filename);
  127. // Set module's filename so relative require can work as expected.
  128. global.module.filename = global.__filename;
  129. // Also search for module under the html file.
  130. global.module.paths = Module._nodeModulePaths(global.__dirname);
  131. } else {
  132. // For backwards compatibility we fake these two paths here
  133. global.__filename = path.join(process.resourcesPath, 'electron.asar', 'renderer', 'init.js');
  134. global.__dirname = path.join(process.resourcesPath, 'electron.asar', 'renderer');
  135. if (appPath) {
  136. // Search for module under the app directory
  137. global.module.paths = Module._nodeModulePaths(appPath);
  138. }
  139. }
  140. // Redirect window.onerror to uncaughtException.
  141. window.onerror = function (_message, _filename, _lineno, _colno, error) {
  142. if (global.process.listenerCount('uncaughtException') > 0) {
  143. // We do not want to add `uncaughtException` to our definitions
  144. // because we don't want anyone else (anywhere) to throw that kind
  145. // of error.
  146. global.process.emit('uncaughtException' as any, error as any);
  147. return true;
  148. } else {
  149. return false;
  150. }
  151. };
  152. } else {
  153. // Delete Node's symbols after the Environment has been loaded in a
  154. // non context-isolated environment
  155. if (!contextIsolation) {
  156. process.once('loaded', function () {
  157. delete global.process;
  158. delete global.Buffer;
  159. delete global.setImmediate;
  160. delete global.clearImmediate;
  161. delete global.global;
  162. delete global.root;
  163. delete global.GLOBAL;
  164. });
  165. }
  166. }
  167. const errorUtils = require('@electron/internal/common/error-utils');
  168. // Load the preload scripts.
  169. for (const preloadScript of preloadScripts) {
  170. try {
  171. Module._load(preloadScript);
  172. } catch (error) {
  173. console.error(`Unable to load preload script: ${preloadScript}`);
  174. console.error(error);
  175. ipcRendererInternal.send('ELECTRON_BROWSER_PRELOAD_ERROR', preloadScript, errorUtils.serialize(error));
  176. }
  177. }
  178. // Warn about security issues
  179. if (process.isMainFrame) {
  180. const { securityWarnings } = require('@electron/internal/renderer/security-warnings');
  181. securityWarnings(nodeIntegration);
  182. }