web-contents.ts 29 KB

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