web-contents.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. import { app, ipcMain, session, webFrameMain } from 'electron/main';
  2. import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main';
  3. import * as url from 'url';
  4. import * as path from 'path';
  5. import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager';
  6. import { parseFeatures } from '@electron/internal/browser/parse-features-string';
  7. import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
  8. import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils';
  9. import { MessagePortMain } from '@electron/internal/browser/message-port-main';
  10. import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
  11. import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl';
  12. import * as deprecate from '@electron/internal/common/deprecate';
  13. // session is not used here, the purpose is to make sure session is initialized
  14. // before the webContents module.
  15. // eslint-disable-next-line no-unused-expressions
  16. session;
  17. const webFrameMainBinding = process._linkedBinding('electron_browser_web_frame_main');
  18. let nextId = 0;
  19. const getNextId = function () {
  20. return ++nextId;
  21. };
  22. type PostData = LoadURLOptions['postData']
  23. // Stock page sizes
  24. const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = {
  25. Letter: {
  26. custom_display_name: 'Letter',
  27. height_microns: 279400,
  28. name: 'NA_LETTER',
  29. width_microns: 215900
  30. },
  31. Legal: {
  32. custom_display_name: 'Legal',
  33. height_microns: 355600,
  34. name: 'NA_LEGAL',
  35. width_microns: 215900
  36. },
  37. Tabloid: {
  38. height_microns: 431800,
  39. name: 'NA_LEDGER',
  40. width_microns: 279400,
  41. custom_display_name: 'Tabloid'
  42. },
  43. A0: {
  44. custom_display_name: 'A0',
  45. height_microns: 1189000,
  46. name: 'ISO_A0',
  47. width_microns: 841000
  48. },
  49. A1: {
  50. custom_display_name: 'A1',
  51. height_microns: 841000,
  52. name: 'ISO_A1',
  53. width_microns: 594000
  54. },
  55. A2: {
  56. custom_display_name: 'A2',
  57. height_microns: 594000,
  58. name: 'ISO_A2',
  59. width_microns: 420000
  60. },
  61. A3: {
  62. custom_display_name: 'A3',
  63. height_microns: 420000,
  64. name: 'ISO_A3',
  65. width_microns: 297000
  66. },
  67. A4: {
  68. custom_display_name: 'A4',
  69. height_microns: 297000,
  70. name: 'ISO_A4',
  71. is_default: 'true',
  72. width_microns: 210000
  73. },
  74. A5: {
  75. custom_display_name: 'A5',
  76. height_microns: 210000,
  77. name: 'ISO_A5',
  78. width_microns: 148000
  79. },
  80. A6: {
  81. custom_display_name: 'A6',
  82. height_microns: 148000,
  83. name: 'ISO_A6',
  84. width_microns: 105000
  85. }
  86. } as const;
  87. const paperFormats: Record<string, ElectronInternal.PageSize> = {
  88. letter: { width: 8.5, height: 11 },
  89. legal: { width: 8.5, height: 14 },
  90. tabloid: { width: 11, height: 17 },
  91. ledger: { width: 17, height: 11 },
  92. a0: { width: 33.1, height: 46.8 },
  93. a1: { width: 23.4, height: 33.1 },
  94. a2: { width: 16.54, height: 23.4 },
  95. a3: { width: 11.7, height: 16.54 },
  96. a4: { width: 8.27, height: 11.7 },
  97. a5: { width: 5.83, height: 8.27 },
  98. a6: { width: 4.13, height: 5.83 }
  99. } as const;
  100. // The minimum micron size Chromium accepts is that where:
  101. // Per printing/units.h:
  102. // * kMicronsPerInch - Length of an inch in 0.001mm unit.
  103. // * kPointsPerInch - Length of an inch in CSS's 1pt unit.
  104. //
  105. // Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1
  106. //
  107. // Practically, this means microns need to be > 352 microns.
  108. // We therefore need to verify this or it will silently fail.
  109. const isValidCustomPageSize = (width: number, height: number) => {
  110. return [width, height].every(x => x > 352);
  111. };
  112. // JavaScript implementations of WebContents.
  113. const binding = process._linkedBinding('electron_browser_web_contents');
  114. const printing = process._linkedBinding('electron_browser_printing');
  115. const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } };
  116. WebContents.prototype.postMessage = function (...args) {
  117. return this.mainFrame.postMessage(...args);
  118. };
  119. WebContents.prototype.send = function (channel, ...args) {
  120. return this.mainFrame.send(channel, ...args);
  121. };
  122. WebContents.prototype._sendInternal = function (channel, ...args) {
  123. return this.mainFrame._sendInternal(channel, ...args);
  124. };
  125. function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) {
  126. if (typeof frame === 'number') {
  127. return webFrameMain.fromId(contents.mainFrame.processId, frame);
  128. } else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) {
  129. return webFrameMain.fromId(frame[0], frame[1]);
  130. } else {
  131. throw new Error('Missing required frame argument (must be number or [processId, frameId])');
  132. }
  133. }
  134. WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
  135. const frame = getWebFrame(this, frameId);
  136. if (!frame) return false;
  137. frame.send(channel, ...args);
  138. return true;
  139. };
  140. // Following methods are mapped to webFrame.
  141. const webFrameMethods = [
  142. 'insertCSS',
  143. 'insertText',
  144. 'removeInsertedCSS',
  145. 'setVisualZoomLevelLimits'
  146. ] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[];
  147. for (const method of webFrameMethods) {
  148. WebContents.prototype[method] = function (...args: any[]): Promise<any> {
  149. return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args);
  150. };
  151. }
  152. const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => {
  153. if (webContents.getURL() && !webContents.isLoadingMainFrame()) return;
  154. return new Promise<void>((resolve) => {
  155. webContents.once('did-stop-loading', () => {
  156. resolve();
  157. });
  158. });
  159. };
  160. // Make sure WebContents::executeJavaScript would run the code only when the
  161. // WebContents has been loaded.
  162. WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) {
  163. await waitTillCanExecuteJavaScript(this);
  164. return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture);
  165. };
  166. WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) {
  167. await waitTillCanExecuteJavaScript(this);
  168. return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture);
  169. };
  170. function checkType<T> (value: T, type: 'number' | 'boolean' | 'string' | 'object', name: string): T {
  171. // eslint-disable-next-line valid-typeof
  172. if (typeof value !== type) {
  173. throw new TypeError(`${name} must be a ${type}`);
  174. }
  175. return value;
  176. }
  177. function parsePageSize (pageSize: string | ElectronInternal.PageSize) {
  178. if (typeof pageSize === 'string') {
  179. const format = paperFormats[pageSize.toLowerCase()];
  180. if (!format) {
  181. throw new Error(`Invalid pageSize ${pageSize}`);
  182. }
  183. return { paperWidth: format.width, paperHeight: format.height };
  184. } else if (typeof pageSize === 'object') {
  185. if (typeof pageSize.width !== 'number' || typeof pageSize.height !== 'number') {
  186. throw new TypeError('width and height properties are required for pageSize');
  187. }
  188. return { paperWidth: pageSize.width, paperHeight: pageSize.height };
  189. } else {
  190. throw new TypeError('pageSize must be a string or an object');
  191. }
  192. }
  193. // Translate the options of printToPDF.
  194. let pendingPromise: Promise<any> | undefined;
  195. WebContents.prototype.printToPDF = async function (options) {
  196. const margins = checkType(options.margins ?? {}, 'object', 'margins');
  197. const printSettings = {
  198. requestID: getNextId(),
  199. landscape: checkType(options.landscape ?? false, 'boolean', 'landscape'),
  200. displayHeaderFooter: checkType(options.displayHeaderFooter ?? false, 'boolean', 'displayHeaderFooter'),
  201. headerTemplate: checkType(options.headerTemplate ?? '', 'string', 'headerTemplate'),
  202. footerTemplate: checkType(options.footerTemplate ?? '', 'string', 'footerTemplate'),
  203. printBackground: checkType(options.printBackground ?? false, 'boolean', 'printBackground'),
  204. scale: checkType(options.scale ?? 1.0, 'number', 'scale'),
  205. marginTop: checkType(margins.top ?? 0.4, 'number', 'margins.top'),
  206. marginBottom: checkType(margins.bottom ?? 0.4, 'number', 'margins.bottom'),
  207. marginLeft: checkType(margins.left ?? 0.4, 'number', 'margins.left'),
  208. marginRight: checkType(margins.right ?? 0.4, 'number', 'margins.right'),
  209. pageRanges: checkType(options.pageRanges ?? '', 'string', 'pageRanges'),
  210. preferCSSPageSize: checkType(options.preferCSSPageSize ?? false, 'boolean', 'preferCSSPageSize'),
  211. generateTaggedPDF: checkType(options.generateTaggedPDF ?? false, 'boolean', 'generateTaggedPDF'),
  212. ...parsePageSize(options.pageSize ?? 'letter')
  213. };
  214. if (this._printToPDF) {
  215. if (pendingPromise) {
  216. pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings));
  217. } else {
  218. pendingPromise = this._printToPDF(printSettings);
  219. }
  220. return pendingPromise;
  221. } else {
  222. throw new Error('Printing feature is disabled');
  223. }
  224. };
  225. // TODO(codebytere): deduplicate argument sanitization by moving rest of
  226. // print param logic into new file shared between printToPDF and print
  227. WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions, callback) {
  228. if (typeof options !== 'object') {
  229. throw new TypeError('webContents.print(): Invalid print settings specified.');
  230. }
  231. const printSettings: Record<string, any> = { ...options };
  232. const pageSize = options.pageSize ?? 'A4';
  233. if (typeof pageSize === 'object') {
  234. if (!pageSize.height || !pageSize.width) {
  235. throw new Error('height and width properties are required for pageSize');
  236. }
  237. // Dimensions in Microns - 1 meter = 10^6 microns
  238. const height = Math.ceil(pageSize.height);
  239. const width = Math.ceil(pageSize.width);
  240. if (!isValidCustomPageSize(width, height)) {
  241. throw new RangeError('height and width properties must be minimum 352 microns.');
  242. }
  243. printSettings.mediaSize = {
  244. name: 'CUSTOM',
  245. custom_display_name: 'Custom',
  246. height_microns: height,
  247. width_microns: width,
  248. imageable_area_left_microns: 0,
  249. imageable_area_bottom_microns: 0,
  250. imageable_area_right_microns: width,
  251. imageable_area_top_microns: height
  252. };
  253. } else if (typeof pageSize === 'string' && PDFPageSizes[pageSize]) {
  254. const mediaSize = PDFPageSizes[pageSize];
  255. printSettings.mediaSize = {
  256. ...mediaSize,
  257. imageable_area_left_microns: 0,
  258. imageable_area_bottom_microns: 0,
  259. imageable_area_right_microns: mediaSize.width_microns,
  260. imageable_area_top_microns: mediaSize.height_microns
  261. };
  262. } else {
  263. throw new Error(`Unsupported pageSize: ${pageSize}`);
  264. }
  265. if (this._print) {
  266. if (callback) {
  267. this._print(printSettings, callback);
  268. } else {
  269. this._print(printSettings);
  270. }
  271. } else {
  272. console.error('Error: Printing feature is disabled.');
  273. }
  274. };
  275. WebContents.prototype.getPrintersAsync = async function () {
  276. // TODO(nornagon): this API has nothing to do with WebContents and should be
  277. // moved.
  278. if (printing.getPrinterListAsync) {
  279. return printing.getPrinterListAsync();
  280. } else {
  281. console.error('Error: Printing feature is disabled.');
  282. return [];
  283. }
  284. };
  285. WebContents.prototype.loadFile = function (filePath, options = {}) {
  286. if (typeof filePath !== 'string') {
  287. throw new TypeError('Must pass filePath as a string');
  288. }
  289. const { query, search, hash } = options;
  290. return this.loadURL(url.format({
  291. protocol: 'file',
  292. slashes: true,
  293. pathname: path.resolve(app.getAppPath(), filePath),
  294. query,
  295. search,
  296. hash
  297. }));
  298. };
  299. WebContents.prototype.loadURL = function (url, options) {
  300. const p = new Promise<void>((resolve, reject) => {
  301. const resolveAndCleanup = () => {
  302. removeListeners();
  303. resolve();
  304. };
  305. const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => {
  306. const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
  307. Object.assign(err, { errno: errorCode, code: errorDescription, url });
  308. removeListeners();
  309. reject(err);
  310. };
  311. const finishListener = () => {
  312. resolveAndCleanup();
  313. };
  314. const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
  315. if (isMainFrame) {
  316. rejectAndCleanup(errorCode, errorDescription, validatedURL);
  317. }
  318. };
  319. let navigationStarted = false;
  320. let browserInitiatedInPageNavigation = false;
  321. const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
  322. if (isMainFrame) {
  323. if (navigationStarted && !isSameDocument) {
  324. // the webcontents has started another unrelated navigation in the
  325. // main frame (probably from the app calling `loadURL` again); reject
  326. // the promise
  327. // We should only consider the request aborted if the "navigation" is
  328. // actually navigating and not simply transitioning URL state in the
  329. // current context. E.g. pushState and `location.hash` changes are
  330. // considered navigation events but are triggered with isSameDocument.
  331. // We can ignore these to allow virtual routing on page load as long
  332. // as the routing does not leave the document
  333. return rejectAndCleanup(-3, 'ERR_ABORTED', url);
  334. }
  335. browserInitiatedInPageNavigation = navigationStarted && isSameDocument;
  336. navigationStarted = true;
  337. }
  338. };
  339. const stopLoadingListener = () => {
  340. // By the time we get here, either 'finish' or 'fail' should have fired
  341. // if the navigation occurred. However, in some situations (e.g. when
  342. // attempting to load a page with a bad scheme), loading will stop
  343. // without emitting finish or fail. In this case, we reject the promise
  344. // with a generic failure.
  345. // TODO(jeremy): enumerate all the cases in which this can happen. If
  346. // the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
  347. // would be more appropriate.
  348. rejectAndCleanup(-2, 'ERR_FAILED', url);
  349. };
  350. const finishListenerWhenUserInitiatedNavigation = () => {
  351. if (!browserInitiatedInPageNavigation) {
  352. finishListener();
  353. }
  354. };
  355. const removeListeners = () => {
  356. this.removeListener('did-finish-load', finishListener);
  357. this.removeListener('did-fail-load', failListener);
  358. this.removeListener('did-navigate-in-page', finishListenerWhenUserInitiatedNavigation);
  359. this.removeListener('did-start-navigation', navigationListener);
  360. this.removeListener('did-stop-loading', stopLoadingListener);
  361. this.removeListener('destroyed', stopLoadingListener);
  362. };
  363. this.on('did-finish-load', finishListener);
  364. this.on('did-fail-load', failListener);
  365. this.on('did-navigate-in-page', finishListenerWhenUserInitiatedNavigation);
  366. this.on('did-start-navigation', navigationListener);
  367. this.on('did-stop-loading', stopLoadingListener);
  368. this.on('destroyed', stopLoadingListener);
  369. });
  370. // Add a no-op rejection handler to silence the unhandled rejection error.
  371. p.catch(() => {});
  372. this._loadURL(url, options ?? {});
  373. return p;
  374. };
  375. WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, outlivesOpener?: boolean})) {
  376. this._windowOpenHandler = handler;
  377. };
  378. WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): {browserWindowConstructorOptions: BrowserWindowConstructorOptions | null, outlivesOpener: boolean} {
  379. const defaultResponse = {
  380. browserWindowConstructorOptions: null,
  381. outlivesOpener: false
  382. };
  383. if (!this._windowOpenHandler) {
  384. return defaultResponse;
  385. }
  386. const response = this._windowOpenHandler(details);
  387. if (typeof response !== 'object') {
  388. event.preventDefault();
  389. console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`);
  390. return defaultResponse;
  391. }
  392. if (response === null) {
  393. event.preventDefault();
  394. console.error('The window open handler response must be an object, but was instead null.');
  395. return defaultResponse;
  396. }
  397. if (response.action === 'deny') {
  398. event.preventDefault();
  399. return defaultResponse;
  400. } else if (response.action === 'allow') {
  401. return {
  402. browserWindowConstructorOptions: typeof response.overrideBrowserWindowOptions === 'object' ? response.overrideBrowserWindowOptions : null,
  403. outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false
  404. };
  405. } else {
  406. event.preventDefault();
  407. console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.');
  408. return defaultResponse;
  409. }
  410. };
  411. const addReplyToEvent = (event: Electron.IpcMainEvent) => {
  412. const { processId, frameId } = event;
  413. event.reply = (channel: string, ...args: any[]) => {
  414. event.sender.sendToFrame([processId, frameId], channel, ...args);
  415. };
  416. };
  417. const addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => {
  418. event.sender = sender;
  419. const { processId, frameId } = event;
  420. Object.defineProperty(event, 'senderFrame', {
  421. get: () => webFrameMain.fromId(processId, frameId)
  422. });
  423. };
  424. const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
  425. Object.defineProperty(event, 'returnValue', {
  426. set: (value) => event._replyChannel.sendReply(value),
  427. get: () => {}
  428. });
  429. };
  430. const getWebFrameForEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
  431. if (!event.processId || !event.frameId) return null;
  432. return webFrameMainBinding.fromIdOrNull(event.processId, event.frameId);
  433. };
  434. const commandLine = process._linkedBinding('electron_common_command_line');
  435. const environment = process._linkedBinding('electron_common_environment');
  436. const loggingEnabled = () => {
  437. return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging');
  438. };
  439. // Add JavaScript wrappers for WebContents class.
  440. WebContents.prototype._init = function () {
  441. const prefs = this.getLastWebPreferences() || {};
  442. if (!prefs.nodeIntegration && prefs.preload != null && prefs.sandbox == null) {
  443. deprecate.log('The default sandbox option for windows without nodeIntegration is changing. Presently, by default, when a window has a preload script, it defaults to being unsandboxed. In Electron 20, this default will be changing, and all windows that have nodeIntegration: false (which is the default) will be sandboxed by default. If your preload script doesn\'t use Node, no action is needed. If your preload script does use Node, either refactor it to move Node usage to the main process, or specify sandbox: false in your WebPreferences.');
  444. }
  445. // Read off the ID at construction time, so that it's accessible even after
  446. // the underlying C++ WebContents is destroyed.
  447. const id = this.id;
  448. Object.defineProperty(this, 'id', {
  449. value: id,
  450. writable: false
  451. });
  452. this._windowOpenHandler = null;
  453. const ipc = new IpcMainImpl();
  454. Object.defineProperty(this, 'ipc', {
  455. get () { return ipc; },
  456. enumerable: true
  457. });
  458. // Dispatch IPC messages to the ipc module.
  459. this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
  460. addSenderToEvent(event, this);
  461. if (internal) {
  462. ipcMainInternal.emit(channel, event, ...args);
  463. } else {
  464. addReplyToEvent(event);
  465. this.emit('ipc-message', event, channel, ...args);
  466. const maybeWebFrame = getWebFrameForEvent(event);
  467. maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
  468. ipc.emit(channel, event, ...args);
  469. ipcMain.emit(channel, event, ...args);
  470. }
  471. });
  472. this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
  473. addSenderToEvent(event, this);
  474. const replyWithResult = (result: any) => event._replyChannel.sendReply({ result });
  475. const replyWithError = (error: Error) => {
  476. console.error(`Error occurred in handler for '${channel}':`, error);
  477. event._replyChannel.sendReply({ error: error.toString() });
  478. };
  479. const maybeWebFrame = getWebFrameForEvent(event);
  480. const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain];
  481. const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel));
  482. if (target) {
  483. const handler = (target as any)._invokeHandlers.get(channel);
  484. try {
  485. replyWithResult(await Promise.resolve(handler(event, ...args)));
  486. } catch (err) {
  487. replyWithError(err as Error);
  488. }
  489. } else {
  490. replyWithError(new Error(`No handler registered for '${channel}'`));
  491. }
  492. });
  493. this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
  494. addSenderToEvent(event, this);
  495. addReturnValueToEvent(event);
  496. if (internal) {
  497. ipcMainInternal.emit(channel, event, ...args);
  498. } else {
  499. addReplyToEvent(event);
  500. const maybeWebFrame = getWebFrameForEvent(event);
  501. if (this.listenerCount('ipc-message-sync') === 0 && ipc.listenerCount(channel) === 0 && ipcMain.listenerCount(channel) === 0 && (!maybeWebFrame || maybeWebFrame.ipc.listenerCount(channel) === 0)) {
  502. console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`);
  503. }
  504. this.emit('ipc-message-sync', event, channel, ...args);
  505. maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
  506. ipc.emit(channel, event, ...args);
  507. ipcMain.emit(channel, event, ...args);
  508. }
  509. });
  510. this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
  511. addSenderToEvent(event, this);
  512. event.ports = ports.map(p => new MessagePortMain(p));
  513. const maybeWebFrame = getWebFrameForEvent(event);
  514. maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message);
  515. ipc.emit(channel, event, message);
  516. ipcMain.emit(channel, event, message);
  517. });
  518. this.on('render-process-gone', (event, details) => {
  519. app.emit('render-process-gone', event, this, details);
  520. // Log out a hint to help users better debug renderer crashes.
  521. if (loggingEnabled()) {
  522. console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`);
  523. }
  524. });
  525. // The devtools requests the webContents to reload.
  526. this.on('devtools-reload-page', function (this: Electron.WebContents) {
  527. this.reload();
  528. });
  529. if (this.getType() !== 'remote') {
  530. // Make new windows requested by links behave like "window.open".
  531. this.on('-new-window' as any, (event: Electron.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
  532. rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
  533. const postBody = postData ? {
  534. data: postData,
  535. ...parseContentTypeFormat(postData)
  536. } : undefined;
  537. const details: Electron.HandlerDetails = {
  538. url,
  539. frameName,
  540. features: rawFeatures,
  541. referrer,
  542. postBody,
  543. disposition
  544. };
  545. let result: ReturnType<typeof this._callWindowOpenHandler>;
  546. try {
  547. result = this._callWindowOpenHandler(event, details);
  548. } catch (err) {
  549. event.preventDefault();
  550. throw err;
  551. }
  552. const options = result.browserWindowConstructorOptions;
  553. if (!event.defaultPrevented) {
  554. openGuestWindow({
  555. embedder: this,
  556. disposition,
  557. referrer,
  558. postData,
  559. overrideBrowserWindowOptions: options || {},
  560. windowOpenArgs: details,
  561. outlivesOpener: result.outlivesOpener
  562. });
  563. }
  564. });
  565. let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
  566. let windowOpenOutlivesOpenerOption: boolean = false;
  567. this.on('-will-add-new-contents' as any, (event: Electron.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
  568. const postBody = postData ? {
  569. data: postData,
  570. ...parseContentTypeFormat(postData)
  571. } : undefined;
  572. const details: Electron.HandlerDetails = {
  573. url,
  574. frameName,
  575. features: rawFeatures,
  576. disposition,
  577. referrer,
  578. postBody
  579. };
  580. let result: ReturnType<typeof this._callWindowOpenHandler>;
  581. try {
  582. result = this._callWindowOpenHandler(event, details);
  583. } catch (err) {
  584. event.preventDefault();
  585. throw err;
  586. }
  587. windowOpenOutlivesOpenerOption = result.outlivesOpener;
  588. windowOpenOverriddenOptions = result.browserWindowConstructorOptions;
  589. if (!event.defaultPrevented) {
  590. const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
  591. // Allow setting of backgroundColor as a webPreference even though
  592. // it's technically a BrowserWindowConstructorOptions option because
  593. // we need to access it in the renderer at init time.
  594. backgroundColor: windowOpenOverriddenOptions.backgroundColor,
  595. transparent: windowOpenOverriddenOptions.transparent,
  596. ...windowOpenOverriddenOptions.webPreferences
  597. } : undefined;
  598. const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
  599. const webPreferences = makeWebPreferences({
  600. embedder: this,
  601. insecureParsedWebPreferences: parsedWebPreferences,
  602. secureOverrideWebPreferences
  603. });
  604. windowOpenOverriddenOptions = {
  605. ...windowOpenOverriddenOptions,
  606. webPreferences
  607. };
  608. this._setNextChildWebPreferences(webPreferences);
  609. }
  610. });
  611. // Create a new browser window for "window.open"
  612. this.on('-add-new-contents' as any, (event: Electron.Event, webContents: Electron.WebContents, disposition: string,
  613. _userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
  614. referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
  615. const overriddenOptions = windowOpenOverriddenOptions || undefined;
  616. const outlivesOpener = windowOpenOutlivesOpenerOption;
  617. windowOpenOverriddenOptions = null;
  618. // false is the default
  619. windowOpenOutlivesOpenerOption = false;
  620. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  621. disposition !== 'background-tab')) {
  622. event.preventDefault();
  623. return;
  624. }
  625. openGuestWindow({
  626. embedder: this,
  627. guest: webContents,
  628. overrideBrowserWindowOptions: overriddenOptions,
  629. disposition,
  630. referrer,
  631. postData,
  632. windowOpenArgs: {
  633. url,
  634. frameName,
  635. features: rawFeatures
  636. },
  637. outlivesOpener
  638. });
  639. });
  640. }
  641. this.on('login', (event, ...args) => {
  642. app.emit('login', event, this, ...args);
  643. });
  644. this.on('ready-to-show' as any, () => {
  645. const owner = this.getOwnerBrowserWindow();
  646. if (owner && !owner.isDestroyed()) {
  647. process.nextTick(() => {
  648. owner.emit('ready-to-show');
  649. });
  650. }
  651. });
  652. this.on('select-bluetooth-device', (event, devices, callback) => {
  653. if (this.listenerCount('select-bluetooth-device') === 1) {
  654. // Cancel it if there are no handlers
  655. event.preventDefault();
  656. callback('');
  657. }
  658. });
  659. app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, this);
  660. // Properties
  661. Object.defineProperty(this, 'audioMuted', {
  662. get: () => this.isAudioMuted(),
  663. set: (muted) => this.setAudioMuted(muted)
  664. });
  665. Object.defineProperty(this, 'userAgent', {
  666. get: () => this.getUserAgent(),
  667. set: (agent) => this.setUserAgent(agent)
  668. });
  669. Object.defineProperty(this, 'zoomLevel', {
  670. get: () => this.getZoomLevel(),
  671. set: (level) => this.setZoomLevel(level)
  672. });
  673. Object.defineProperty(this, 'zoomFactor', {
  674. get: () => this.getZoomFactor(),
  675. set: (factor) => this.setZoomFactor(factor)
  676. });
  677. Object.defineProperty(this, 'frameRate', {
  678. get: () => this.getFrameRate(),
  679. set: (rate) => this.setFrameRate(rate)
  680. });
  681. Object.defineProperty(this, 'backgroundThrottling', {
  682. get: () => this.getBackgroundThrottling(),
  683. set: (allowed) => this.setBackgroundThrottling(allowed)
  684. });
  685. };
  686. // Public APIs.
  687. export function create (options = {}): Electron.WebContents {
  688. return new (WebContents as any)(options);
  689. }
  690. export function fromId (id: string) {
  691. return binding.fromId(id);
  692. }
  693. export function fromFrame (frame: Electron.WebFrameMain) {
  694. return binding.fromFrame(frame);
  695. }
  696. export function fromDevToolsTargetId (targetId: string) {
  697. return binding.fromDevToolsTargetId(targetId);
  698. }
  699. export function getFocusedWebContents () {
  700. let focused = null;
  701. for (const contents of binding.getAllWebContents()) {
  702. if (!contents.isFocused()) continue;
  703. if (focused == null) focused = contents;
  704. // Return webview web contents which may be embedded inside another
  705. // web contents that is also reporting as focused
  706. if (contents.getType() === 'webview') return contents;
  707. }
  708. return focused;
  709. }
  710. export function getAllWebContents () {
  711. return binding.getAllWebContents();
  712. }