web-contents.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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/common/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 initalized
  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. // The minimum micron size Chromium accepts is that where:
  61. // Per printing/units.h:
  62. // * kMicronsPerInch - Length of an inch in 0.001mm unit.
  63. // * kPointsPerInch - Length of an inch in CSS's 1pt unit.
  64. //
  65. // Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1
  66. //
  67. // Practically, this means microns need to be > 352 microns.
  68. // We therefore need to verify this or it will silently fail.
  69. const isValidCustomPageSize = (width: number, height: number) => {
  70. return [width, height].every(x => x > 352);
  71. };
  72. // Default printing setting
  73. const defaultPrintingSetting = {
  74. // Customizable.
  75. pageRange: [] as {from: number, to: number}[],
  76. mediaSize: {} as ElectronInternal.MediaSize,
  77. landscape: false,
  78. headerFooterEnabled: false,
  79. marginsType: 0,
  80. scaleFactor: 100,
  81. shouldPrintBackgrounds: false,
  82. shouldPrintSelectionOnly: false,
  83. // Non-customizable.
  84. printWithCloudPrint: false,
  85. printWithPrivet: false,
  86. printWithExtension: false,
  87. pagesPerSheet: 1,
  88. isFirstRequest: false,
  89. previewUIID: 0,
  90. // True, if the document source is modifiable. e.g. HTML and not PDF.
  91. previewModifiable: true,
  92. printToPDF: true,
  93. deviceName: 'Save as PDF',
  94. generateDraftData: true,
  95. dpiHorizontal: 72,
  96. dpiVertical: 72,
  97. rasterizePDF: false,
  98. duplex: 0,
  99. copies: 1,
  100. // 2 = color - see ColorModel in //printing/print_job_constants.h
  101. color: 2,
  102. collate: true,
  103. printerType: 2,
  104. title: undefined as string | undefined,
  105. url: undefined as string | undefined
  106. } as const;
  107. // JavaScript implementations of WebContents.
  108. const binding = process._linkedBinding('electron_browser_web_contents');
  109. const printing = process._linkedBinding('electron_browser_printing');
  110. const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } };
  111. WebContents.prototype.postMessage = function (...args) {
  112. return this.mainFrame.postMessage(...args);
  113. };
  114. WebContents.prototype.send = function (channel, ...args) {
  115. return this.mainFrame.send(channel, ...args);
  116. };
  117. WebContents.prototype._sendInternal = function (channel, ...args) {
  118. return this.mainFrame._sendInternal(channel, ...args);
  119. };
  120. function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) {
  121. if (typeof frame === 'number') {
  122. return webFrameMain.fromId(contents.mainFrame.processId, frame);
  123. } else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) {
  124. return webFrameMain.fromId(frame[0], frame[1]);
  125. } else {
  126. throw new Error('Missing required frame argument (must be number or [processId, frameId])');
  127. }
  128. }
  129. WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
  130. const frame = getWebFrame(this, frameId);
  131. if (!frame) return false;
  132. frame.send(channel, ...args);
  133. return true;
  134. };
  135. WebContents.prototype._sendToFrameInternal = function (frameId, channel, ...args) {
  136. const frame = getWebFrame(this, frameId);
  137. if (!frame) return false;
  138. frame._sendInternal(channel, ...args);
  139. return true;
  140. };
  141. // Following methods are mapped to webFrame.
  142. const webFrameMethods = [
  143. 'insertCSS',
  144. 'insertText',
  145. 'removeInsertedCSS',
  146. 'setVisualZoomLevelLimits'
  147. ] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[];
  148. for (const method of webFrameMethods) {
  149. WebContents.prototype[method] = function (...args: any[]): Promise<any> {
  150. return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args);
  151. };
  152. }
  153. const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => {
  154. if (webContents.getURL() && !webContents.isLoadingMainFrame()) return;
  155. return new Promise<void>((resolve) => {
  156. webContents.once('did-stop-loading', () => {
  157. resolve();
  158. });
  159. });
  160. };
  161. // Make sure WebContents::executeJavaScript would run the code only when the
  162. // WebContents has been loaded.
  163. WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) {
  164. await waitTillCanExecuteJavaScript(this);
  165. return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture);
  166. };
  167. WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) {
  168. await waitTillCanExecuteJavaScript(this);
  169. return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture);
  170. };
  171. // Translate the options of printToPDF.
  172. let pendingPromise: Promise<any> | undefined;
  173. WebContents.prototype.printToPDF = async function (options) {
  174. const printSettings: Record<string, any> = {
  175. ...defaultPrintingSetting,
  176. requestID: getNextId()
  177. };
  178. if (options.landscape !== undefined) {
  179. if (typeof options.landscape !== 'boolean') {
  180. const error = new Error('landscape must be a Boolean');
  181. return Promise.reject(error);
  182. }
  183. printSettings.landscape = options.landscape;
  184. }
  185. if (options.scaleFactor !== undefined) {
  186. if (typeof options.scaleFactor !== 'number') {
  187. const error = new Error('scaleFactor must be a Number');
  188. return Promise.reject(error);
  189. }
  190. printSettings.scaleFactor = options.scaleFactor;
  191. }
  192. if (options.marginsType !== undefined) {
  193. if (typeof options.marginsType !== 'number') {
  194. const error = new Error('marginsType must be a Number');
  195. return Promise.reject(error);
  196. }
  197. printSettings.marginsType = options.marginsType;
  198. }
  199. if (options.printSelectionOnly !== undefined) {
  200. if (typeof options.printSelectionOnly !== 'boolean') {
  201. const error = new Error('printSelectionOnly must be a Boolean');
  202. return Promise.reject(error);
  203. }
  204. printSettings.shouldPrintSelectionOnly = options.printSelectionOnly;
  205. }
  206. if (options.printBackground !== undefined) {
  207. if (typeof options.printBackground !== 'boolean') {
  208. const error = new Error('printBackground must be a Boolean');
  209. return Promise.reject(error);
  210. }
  211. printSettings.shouldPrintBackgrounds = options.printBackground;
  212. }
  213. if (options.pageRanges !== undefined) {
  214. const pageRanges = options.pageRanges;
  215. if (!Object.prototype.hasOwnProperty.call(pageRanges, 'from') || !Object.prototype.hasOwnProperty.call(pageRanges, 'to')) {
  216. const error = new Error('pageRanges must be an Object with \'from\' and \'to\' properties');
  217. return Promise.reject(error);
  218. }
  219. if (typeof pageRanges.from !== 'number') {
  220. const error = new Error('pageRanges.from must be a Number');
  221. return Promise.reject(error);
  222. }
  223. if (typeof pageRanges.to !== 'number') {
  224. const error = new Error('pageRanges.to must be a Number');
  225. return Promise.reject(error);
  226. }
  227. // Chromium uses 1-based page ranges, so increment each by 1.
  228. printSettings.pageRange = [{
  229. from: pageRanges.from + 1,
  230. to: pageRanges.to + 1
  231. }];
  232. }
  233. if (options.headerFooter !== undefined) {
  234. const headerFooter = options.headerFooter;
  235. printSettings.headerFooterEnabled = true;
  236. if (typeof headerFooter === 'object') {
  237. if (!headerFooter.url || !headerFooter.title) {
  238. const error = new Error('url and title properties are required for headerFooter');
  239. return Promise.reject(error);
  240. }
  241. if (typeof headerFooter.title !== 'string') {
  242. const error = new Error('headerFooter.title must be a String');
  243. return Promise.reject(error);
  244. }
  245. printSettings.title = headerFooter.title;
  246. if (typeof headerFooter.url !== 'string') {
  247. const error = new Error('headerFooter.url must be a String');
  248. return Promise.reject(error);
  249. }
  250. printSettings.url = headerFooter.url;
  251. } else {
  252. const error = new Error('headerFooter must be an Object');
  253. return Promise.reject(error);
  254. }
  255. }
  256. // Optionally set size for PDF.
  257. if (options.pageSize !== undefined) {
  258. const pageSize = options.pageSize;
  259. if (typeof pageSize === 'object') {
  260. if (!pageSize.height || !pageSize.width) {
  261. const error = new Error('height and width properties are required for pageSize');
  262. return Promise.reject(error);
  263. }
  264. // Dimensions in Microns - 1 meter = 10^6 microns
  265. const height = Math.ceil(pageSize.height);
  266. const width = Math.ceil(pageSize.width);
  267. if (!isValidCustomPageSize(width, height)) {
  268. const error = new Error('height and width properties must be minimum 352 microns.');
  269. return Promise.reject(error);
  270. }
  271. printSettings.mediaSize = {
  272. name: 'CUSTOM',
  273. custom_display_name: 'Custom',
  274. height_microns: height,
  275. width_microns: width
  276. };
  277. } else if (Object.prototype.hasOwnProperty.call(PDFPageSizes, pageSize)) {
  278. printSettings.mediaSize = PDFPageSizes[pageSize];
  279. } else {
  280. const error = new Error(`Unsupported pageSize: ${pageSize}`);
  281. return Promise.reject(error);
  282. }
  283. } else {
  284. printSettings.mediaSize = PDFPageSizes.A4;
  285. }
  286. // Chromium expects this in a 0-100 range number, not as float
  287. printSettings.scaleFactor = Math.ceil(printSettings.scaleFactor) % 100;
  288. // PrinterType enum from //printing/print_job_constants.h
  289. printSettings.printerType = 2;
  290. if (this._printToPDF) {
  291. if (pendingPromise) {
  292. pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings));
  293. } else {
  294. pendingPromise = this._printToPDF(printSettings);
  295. }
  296. return pendingPromise;
  297. } else {
  298. const error = new Error('Printing feature is disabled');
  299. return Promise.reject(error);
  300. }
  301. };
  302. WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions = {}, callback) {
  303. // TODO(codebytere): deduplicate argument sanitization by moving rest of
  304. // print param logic into new file shared between printToPDF and print
  305. if (typeof options === 'object') {
  306. // Optionally set size for PDF.
  307. if (options.pageSize !== undefined) {
  308. const pageSize = options.pageSize;
  309. if (typeof pageSize === 'object') {
  310. if (!pageSize.height || !pageSize.width) {
  311. throw new Error('height and width properties are required for pageSize');
  312. }
  313. // Dimensions in Microns - 1 meter = 10^6 microns
  314. const height = Math.ceil(pageSize.height);
  315. const width = Math.ceil(pageSize.width);
  316. if (!isValidCustomPageSize(width, height)) {
  317. throw new Error('height and width properties must be minimum 352 microns.');
  318. }
  319. options.mediaSize = {
  320. name: 'CUSTOM',
  321. custom_display_name: 'Custom',
  322. height_microns: height,
  323. width_microns: width
  324. };
  325. } else if (PDFPageSizes[pageSize]) {
  326. options.mediaSize = PDFPageSizes[pageSize];
  327. } else {
  328. throw new Error(`Unsupported pageSize: ${pageSize}`);
  329. }
  330. }
  331. }
  332. if (this._print) {
  333. if (callback) {
  334. this._print(options, callback);
  335. } else {
  336. this._print(options);
  337. }
  338. } else {
  339. console.error('Error: Printing feature is disabled.');
  340. }
  341. };
  342. WebContents.prototype.getPrinters = function () {
  343. // TODO(nornagon): this API has nothing to do with WebContents and should be
  344. // moved.
  345. if (printing.getPrinterList) {
  346. return printing.getPrinterList();
  347. } else {
  348. console.error('Error: Printing feature is disabled.');
  349. return [];
  350. }
  351. };
  352. WebContents.prototype.loadFile = function (filePath, options = {}) {
  353. if (typeof filePath !== 'string') {
  354. throw new Error('Must pass filePath as a string');
  355. }
  356. const { query, search, hash } = options;
  357. return this.loadURL(url.format({
  358. protocol: 'file',
  359. slashes: true,
  360. pathname: path.resolve(app.getAppPath(), filePath),
  361. query,
  362. search,
  363. hash
  364. }));
  365. };
  366. WebContents.prototype.loadURL = function (url, options) {
  367. if (!options) {
  368. options = {};
  369. }
  370. const p = new Promise<void>((resolve, reject) => {
  371. const resolveAndCleanup = () => {
  372. removeListeners();
  373. resolve();
  374. };
  375. const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => {
  376. const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
  377. Object.assign(err, { errno: errorCode, code: errorDescription, url });
  378. removeListeners();
  379. reject(err);
  380. };
  381. const finishListener = () => {
  382. resolveAndCleanup();
  383. };
  384. const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
  385. if (isMainFrame) {
  386. rejectAndCleanup(errorCode, errorDescription, validatedURL);
  387. }
  388. };
  389. let navigationStarted = false;
  390. const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
  391. if (isMainFrame) {
  392. if (navigationStarted && !isSameDocument) {
  393. // the webcontents has started another unrelated navigation in the
  394. // main frame (probably from the app calling `loadURL` again); reject
  395. // the promise
  396. // We should only consider the request aborted if the "navigation" is
  397. // actually navigating and not simply transitioning URL state in the
  398. // current context. E.g. pushState and `location.hash` changes are
  399. // considered navigation events but are triggered with isSameDocument.
  400. // We can ignore these to allow virtual routing on page load as long
  401. // as the routing does not leave the document
  402. return rejectAndCleanup(-3, 'ERR_ABORTED', url);
  403. }
  404. navigationStarted = true;
  405. }
  406. };
  407. const stopLoadingListener = () => {
  408. // By the time we get here, either 'finish' or 'fail' should have fired
  409. // if the navigation occurred. However, in some situations (e.g. when
  410. // attempting to load a page with a bad scheme), loading will stop
  411. // without emitting finish or fail. In this case, we reject the promise
  412. // with a generic failure.
  413. // TODO(jeremy): enumerate all the cases in which this can happen. If
  414. // the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
  415. // would be more appropriate.
  416. rejectAndCleanup(-2, 'ERR_FAILED', url);
  417. };
  418. const removeListeners = () => {
  419. this.removeListener('did-finish-load', finishListener);
  420. this.removeListener('did-fail-load', failListener);
  421. this.removeListener('did-start-navigation', navigationListener);
  422. this.removeListener('did-stop-loading', stopLoadingListener);
  423. this.removeListener('destroyed', stopLoadingListener);
  424. };
  425. this.on('did-finish-load', finishListener);
  426. this.on('did-fail-load', failListener);
  427. this.on('did-start-navigation', navigationListener);
  428. this.on('did-stop-loading', stopLoadingListener);
  429. this.on('destroyed', stopLoadingListener);
  430. });
  431. // Add a no-op rejection handler to silence the unhandled rejection error.
  432. p.catch(() => {});
  433. this._loadURL(url, options);
  434. this.emit('load-url', url, options);
  435. return p;
  436. };
  437. WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'allow'} | {action: 'deny', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions})) {
  438. this._windowOpenHandler = handler;
  439. };
  440. WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): BrowserWindowConstructorOptions | null {
  441. if (!this._windowOpenHandler) {
  442. return null;
  443. }
  444. const response = this._windowOpenHandler(details);
  445. if (typeof response !== 'object') {
  446. event.preventDefault();
  447. console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`);
  448. return null;
  449. }
  450. if (response === null) {
  451. event.preventDefault();
  452. console.error('The window open handler response must be an object, but was instead null.');
  453. return null;
  454. }
  455. if (response.action === 'deny') {
  456. event.preventDefault();
  457. return null;
  458. } else if (response.action === 'allow') {
  459. if (typeof response.overrideBrowserWindowOptions === 'object' && response.overrideBrowserWindowOptions !== null) {
  460. return response.overrideBrowserWindowOptions;
  461. } else {
  462. return {};
  463. }
  464. } else {
  465. event.preventDefault();
  466. console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.');
  467. return null;
  468. }
  469. };
  470. const addReplyToEvent = (event: Electron.IpcMainEvent) => {
  471. const { processId, frameId } = event;
  472. event.reply = (channel: string, ...args: any[]) => {
  473. event.sender.sendToFrame([processId, frameId], channel, ...args);
  474. };
  475. };
  476. const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
  477. const { processId, frameId } = event;
  478. Object.defineProperty(event, 'senderFrame', {
  479. get: () => webFrameMain.fromId(processId, frameId)
  480. });
  481. };
  482. const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
  483. Object.defineProperty(event, 'returnValue', {
  484. set: (value) => event.sendReply(value),
  485. get: () => {}
  486. });
  487. };
  488. const commandLine = process._linkedBinding('electron_common_command_line');
  489. const environment = process._linkedBinding('electron_common_environment');
  490. const loggingEnabled = () => {
  491. return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging');
  492. };
  493. // Add JavaScript wrappers for WebContents class.
  494. WebContents.prototype._init = function () {
  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. const options = this._callWindowOpenHandler(event, details);
  578. if (!event.defaultPrevented) {
  579. openGuestWindow({
  580. event,
  581. embedder: event.sender,
  582. disposition,
  583. referrer,
  584. postData,
  585. overrideBrowserWindowOptions: options || {},
  586. windowOpenArgs: details
  587. });
  588. }
  589. });
  590. let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
  591. 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) => {
  592. const postBody = postData ? {
  593. data: postData,
  594. ...parseContentTypeFormat(postData)
  595. } : undefined;
  596. const details: Electron.HandlerDetails = {
  597. url,
  598. frameName,
  599. features: rawFeatures,
  600. disposition,
  601. referrer,
  602. postBody
  603. };
  604. windowOpenOverriddenOptions = this._callWindowOpenHandler(event, details);
  605. if (!event.defaultPrevented) {
  606. const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
  607. // Allow setting of backgroundColor as a webPreference even though
  608. // it's technically a BrowserWindowConstructorOptions option because
  609. // we need to access it in the renderer at init time.
  610. backgroundColor: windowOpenOverriddenOptions.backgroundColor,
  611. transparent: windowOpenOverriddenOptions.transparent,
  612. ...windowOpenOverriddenOptions.webPreferences
  613. } : undefined;
  614. // TODO(zcbenz): The features string is parsed twice: here where it is
  615. // passed to C++, and in |makeBrowserWindowOptions| later where it is
  616. // not actually used since the WebContents is created here.
  617. // We should be able to remove the latter once the |nativeWindowOpen|
  618. // option is removed.
  619. const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
  620. // Parameters should keep same with |makeBrowserWindowOptions|.
  621. const webPreferences = makeWebPreferences({
  622. embedder: event.sender,
  623. insecureParsedWebPreferences: parsedWebPreferences,
  624. secureOverrideWebPreferences
  625. });
  626. this._setNextChildWebPreferences(webPreferences);
  627. }
  628. });
  629. // Create a new browser window for the native implementation of
  630. // "window.open", used in sandbox and nativeWindowOpen mode.
  631. this.on('-add-new-contents' as any, (event: ElectronInternal.Event, webContents: Electron.WebContents, disposition: string,
  632. _userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
  633. referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
  634. const overriddenOptions = windowOpenOverriddenOptions || undefined;
  635. windowOpenOverriddenOptions = null;
  636. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  637. disposition !== 'background-tab')) {
  638. event.preventDefault();
  639. return;
  640. }
  641. openGuestWindow({
  642. event,
  643. embedder: event.sender,
  644. guest: webContents,
  645. overrideBrowserWindowOptions: overriddenOptions,
  646. disposition,
  647. referrer,
  648. postData,
  649. windowOpenArgs: {
  650. url,
  651. frameName,
  652. features: rawFeatures
  653. }
  654. });
  655. });
  656. }
  657. this.on('login', (event, ...args) => {
  658. app.emit('login', event, this, ...args);
  659. });
  660. this.on('ready-to-show' as any, () => {
  661. const owner = this.getOwnerBrowserWindow();
  662. if (owner && !owner.isDestroyed()) {
  663. process.nextTick(() => {
  664. owner.emit('ready-to-show');
  665. });
  666. }
  667. });
  668. this.on('select-bluetooth-device', (event, devices, callback) => {
  669. if (this.listenerCount('select-bluetooth-device') === 1) {
  670. // Cancel it if there are no handlers
  671. event.preventDefault();
  672. callback('');
  673. }
  674. });
  675. const event = process._linkedBinding('electron_browser_event').createEmpty();
  676. app.emit('web-contents-created', event, this);
  677. // Properties
  678. Object.defineProperty(this, 'audioMuted', {
  679. get: () => this.isAudioMuted(),
  680. set: (muted) => this.setAudioMuted(muted)
  681. });
  682. Object.defineProperty(this, 'userAgent', {
  683. get: () => this.getUserAgent(),
  684. set: (agent) => this.setUserAgent(agent)
  685. });
  686. Object.defineProperty(this, 'zoomLevel', {
  687. get: () => this.getZoomLevel(),
  688. set: (level) => this.setZoomLevel(level)
  689. });
  690. Object.defineProperty(this, 'zoomFactor', {
  691. get: () => this.getZoomFactor(),
  692. set: (factor) => this.setZoomFactor(factor)
  693. });
  694. Object.defineProperty(this, 'frameRate', {
  695. get: () => this.getFrameRate(),
  696. set: (rate) => this.setFrameRate(rate)
  697. });
  698. Object.defineProperty(this, 'backgroundThrottling', {
  699. get: () => this.getBackgroundThrottling(),
  700. set: (allowed) => this.setBackgroundThrottling(allowed)
  701. });
  702. };
  703. // Public APIs.
  704. export function create (options = {}): Electron.WebContents {
  705. return new (WebContents as any)(options);
  706. }
  707. export function fromId (id: string) {
  708. return binding.fromId(id);
  709. }
  710. export function fromDevToolsTargetId (targetId: string) {
  711. return binding.fromDevToolsTargetId(targetId);
  712. }
  713. export function getFocusedWebContents () {
  714. let focused = null;
  715. for (const contents of binding.getAllWebContents()) {
  716. if (!contents.isFocused()) continue;
  717. if (focused == null) focused = contents;
  718. // Return webview web contents which may be embedded inside another
  719. // web contents that is also reporting as focused
  720. if (contents.getType() === 'webview') return contents;
  721. }
  722. return focused;
  723. }
  724. export function getAllWebContents () {
  725. return binding.getAllWebContents();
  726. }