web-contents.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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 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.getPrintersAsync = async function () {
  353. // TODO(nornagon): this API has nothing to do with WebContents and should be
  354. // moved.
  355. if (printing.getPrinterListAsync) {
  356. return printing.getPrinterListAsync();
  357. } else {
  358. console.error('Error: Printing feature is disabled.');
  359. return [];
  360. }
  361. };
  362. WebContents.prototype.loadFile = function (filePath, options = {}) {
  363. if (typeof filePath !== 'string') {
  364. throw new Error('Must pass filePath as a string');
  365. }
  366. const { query, search, hash } = options;
  367. return this.loadURL(url.format({
  368. protocol: 'file',
  369. slashes: true,
  370. pathname: path.resolve(app.getAppPath(), filePath),
  371. query,
  372. search,
  373. hash
  374. }));
  375. };
  376. WebContents.prototype.loadURL = function (url, options) {
  377. if (!options) {
  378. options = {};
  379. }
  380. const p = new Promise<void>((resolve, reject) => {
  381. const resolveAndCleanup = () => {
  382. removeListeners();
  383. resolve();
  384. };
  385. const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => {
  386. const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
  387. Object.assign(err, { errno: errorCode, code: errorDescription, url });
  388. removeListeners();
  389. reject(err);
  390. };
  391. const finishListener = () => {
  392. resolveAndCleanup();
  393. };
  394. const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
  395. if (isMainFrame) {
  396. rejectAndCleanup(errorCode, errorDescription, validatedURL);
  397. }
  398. };
  399. let navigationStarted = false;
  400. const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
  401. if (isMainFrame) {
  402. if (navigationStarted && !isSameDocument) {
  403. // the webcontents has started another unrelated navigation in the
  404. // main frame (probably from the app calling `loadURL` again); reject
  405. // the promise
  406. // We should only consider the request aborted if the "navigation" is
  407. // actually navigating and not simply transitioning URL state in the
  408. // current context. E.g. pushState and `location.hash` changes are
  409. // considered navigation events but are triggered with isSameDocument.
  410. // We can ignore these to allow virtual routing on page load as long
  411. // as the routing does not leave the document
  412. return rejectAndCleanup(-3, 'ERR_ABORTED', url);
  413. }
  414. navigationStarted = true;
  415. }
  416. };
  417. const stopLoadingListener = () => {
  418. // By the time we get here, either 'finish' or 'fail' should have fired
  419. // if the navigation occurred. However, in some situations (e.g. when
  420. // attempting to load a page with a bad scheme), loading will stop
  421. // without emitting finish or fail. In this case, we reject the promise
  422. // with a generic failure.
  423. // TODO(jeremy): enumerate all the cases in which this can happen. If
  424. // the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
  425. // would be more appropriate.
  426. rejectAndCleanup(-2, 'ERR_FAILED', url);
  427. };
  428. const removeListeners = () => {
  429. this.removeListener('did-finish-load', finishListener);
  430. this.removeListener('did-fail-load', failListener);
  431. this.removeListener('did-navigate-in-page', finishListener);
  432. this.removeListener('did-start-navigation', navigationListener);
  433. this.removeListener('did-stop-loading', stopLoadingListener);
  434. this.removeListener('destroyed', stopLoadingListener);
  435. };
  436. this.on('did-finish-load', finishListener);
  437. this.on('did-fail-load', failListener);
  438. this.on('did-navigate-in-page', finishListener);
  439. this.on('did-start-navigation', navigationListener);
  440. this.on('did-stop-loading', stopLoadingListener);
  441. this.on('destroyed', stopLoadingListener);
  442. });
  443. // Add a no-op rejection handler to silence the unhandled rejection error.
  444. p.catch(() => {});
  445. this._loadURL(url, options);
  446. this.emit('load-url', url, options);
  447. return p;
  448. };
  449. WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, outlivesOpener?: boolean})) {
  450. this._windowOpenHandler = handler;
  451. };
  452. WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): {browserWindowConstructorOptions: BrowserWindowConstructorOptions | null, outlivesOpener: boolean} {
  453. const defaultResponse = {
  454. browserWindowConstructorOptions: null,
  455. outlivesOpener: false
  456. };
  457. if (!this._windowOpenHandler) {
  458. return defaultResponse;
  459. }
  460. const response = this._windowOpenHandler(details);
  461. if (typeof response !== 'object') {
  462. event.preventDefault();
  463. console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`);
  464. return defaultResponse;
  465. }
  466. if (response === null) {
  467. event.preventDefault();
  468. console.error('The window open handler response must be an object, but was instead null.');
  469. return defaultResponse;
  470. }
  471. if (response.action === 'deny') {
  472. event.preventDefault();
  473. return defaultResponse;
  474. } else if (response.action === 'allow') {
  475. if (typeof response.overrideBrowserWindowOptions === 'object' && response.overrideBrowserWindowOptions !== null) {
  476. return {
  477. browserWindowConstructorOptions: response.overrideBrowserWindowOptions,
  478. outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false
  479. };
  480. } else {
  481. return {
  482. browserWindowConstructorOptions: {},
  483. outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false
  484. };
  485. }
  486. } else {
  487. event.preventDefault();
  488. console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.');
  489. return defaultResponse;
  490. }
  491. };
  492. const addReplyToEvent = (event: Electron.IpcMainEvent) => {
  493. const { processId, frameId } = event;
  494. event.reply = (channel: string, ...args: any[]) => {
  495. event.sender.sendToFrame([processId, frameId], channel, ...args);
  496. };
  497. };
  498. const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
  499. const { processId, frameId } = event;
  500. Object.defineProperty(event, 'senderFrame', {
  501. get: () => webFrameMain.fromId(processId, frameId)
  502. });
  503. };
  504. const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
  505. Object.defineProperty(event, 'returnValue', {
  506. set: (value) => event.sendReply(value),
  507. get: () => {}
  508. });
  509. };
  510. const commandLine = process._linkedBinding('electron_common_command_line');
  511. const environment = process._linkedBinding('electron_common_environment');
  512. const loggingEnabled = () => {
  513. return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging');
  514. };
  515. // Add JavaScript wrappers for WebContents class.
  516. WebContents.prototype._init = function () {
  517. const prefs = this.getLastWebPreferences() || {};
  518. if (!prefs.nodeIntegration && prefs.preload != null && prefs.sandbox == null) {
  519. 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.');
  520. }
  521. // Read off the ID at construction time, so that it's accessible even after
  522. // the underlying C++ WebContents is destroyed.
  523. const id = this.id;
  524. Object.defineProperty(this, 'id', {
  525. value: id,
  526. writable: false
  527. });
  528. this._windowOpenHandler = null;
  529. // Dispatch IPC messages to the ipc module.
  530. this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
  531. addSenderFrameToEvent(event);
  532. if (internal) {
  533. ipcMainInternal.emit(channel, event, ...args);
  534. } else {
  535. addReplyToEvent(event);
  536. this.emit('ipc-message', event, channel, ...args);
  537. ipcMain.emit(channel, event, ...args);
  538. }
  539. });
  540. this.on('-ipc-invoke' as any, function (event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
  541. addSenderFrameToEvent(event);
  542. event._reply = (result: any) => event.sendReply({ result });
  543. event._throw = (error: Error) => {
  544. console.error(`Error occurred in handler for '${channel}':`, error);
  545. event.sendReply({ error: error.toString() });
  546. };
  547. const target = internal ? ipcMainInternal : ipcMain;
  548. if ((target as any)._invokeHandlers.has(channel)) {
  549. (target as any)._invokeHandlers.get(channel)(event, ...args);
  550. } else {
  551. event._throw(`No handler registered for '${channel}'`);
  552. }
  553. });
  554. this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
  555. addSenderFrameToEvent(event);
  556. addReturnValueToEvent(event);
  557. if (internal) {
  558. ipcMainInternal.emit(channel, event, ...args);
  559. } else {
  560. addReplyToEvent(event);
  561. if (this.listenerCount('ipc-message-sync') === 0 && ipcMain.listenerCount(channel) === 0) {
  562. console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`);
  563. }
  564. this.emit('ipc-message-sync', event, channel, ...args);
  565. ipcMain.emit(channel, event, ...args);
  566. }
  567. });
  568. this.on('-ipc-ports' as any, function (event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
  569. addSenderFrameToEvent(event);
  570. event.ports = ports.map(p => new MessagePortMain(p));
  571. ipcMain.emit(channel, event, message);
  572. });
  573. this.on('crashed', (event, ...args) => {
  574. app.emit('renderer-process-crashed', event, this, ...args);
  575. });
  576. this.on('render-process-gone', (event, details) => {
  577. app.emit('render-process-gone', event, this, details);
  578. // Log out a hint to help users better debug renderer crashes.
  579. if (loggingEnabled()) {
  580. console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`);
  581. }
  582. });
  583. // The devtools requests the webContents to reload.
  584. this.on('devtools-reload-page', function (this: Electron.WebContents) {
  585. this.reload();
  586. });
  587. if (this.getType() !== 'remote') {
  588. // Make new windows requested by links behave like "window.open".
  589. this.on('-new-window' as any, (event: ElectronInternal.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
  590. rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
  591. const postBody = postData ? {
  592. data: postData,
  593. ...parseContentTypeFormat(postData)
  594. } : undefined;
  595. const details: Electron.HandlerDetails = {
  596. url,
  597. frameName,
  598. features: rawFeatures,
  599. referrer,
  600. postBody,
  601. disposition
  602. };
  603. let result: ReturnType<typeof this._callWindowOpenHandler>;
  604. try {
  605. result = this._callWindowOpenHandler(event, details);
  606. } catch (err) {
  607. event.preventDefault();
  608. throw err;
  609. }
  610. const options = result.browserWindowConstructorOptions;
  611. if (!event.defaultPrevented) {
  612. openGuestWindow({
  613. event,
  614. embedder: event.sender,
  615. disposition,
  616. referrer,
  617. postData,
  618. overrideBrowserWindowOptions: options || {},
  619. windowOpenArgs: details,
  620. outlivesOpener: result.outlivesOpener
  621. });
  622. }
  623. });
  624. let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
  625. let windowOpenOutlivesOpenerOption: boolean = false;
  626. 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) => {
  627. const postBody = postData ? {
  628. data: postData,
  629. ...parseContentTypeFormat(postData)
  630. } : undefined;
  631. const details: Electron.HandlerDetails = {
  632. url,
  633. frameName,
  634. features: rawFeatures,
  635. disposition,
  636. referrer,
  637. postBody
  638. };
  639. let result: ReturnType<typeof this._callWindowOpenHandler>;
  640. try {
  641. result = this._callWindowOpenHandler(event, details);
  642. } catch (err) {
  643. event.preventDefault();
  644. throw err;
  645. }
  646. windowOpenOutlivesOpenerOption = result.outlivesOpener;
  647. windowOpenOverriddenOptions = result.browserWindowConstructorOptions;
  648. if (!event.defaultPrevented) {
  649. const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
  650. // Allow setting of backgroundColor as a webPreference even though
  651. // it's technically a BrowserWindowConstructorOptions option because
  652. // we need to access it in the renderer at init time.
  653. backgroundColor: windowOpenOverriddenOptions.backgroundColor,
  654. transparent: windowOpenOverriddenOptions.transparent,
  655. ...windowOpenOverriddenOptions.webPreferences
  656. } : undefined;
  657. // TODO(zcbenz): The features string is parsed twice: here where it is
  658. // passed to C++, and in |makeBrowserWindowOptions| later where it is
  659. // not actually used since the WebContents is created here.
  660. // We should be able to remove the latter once the |new-window| event
  661. // is removed.
  662. const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
  663. // Parameters should keep same with |makeBrowserWindowOptions|.
  664. const webPreferences = makeWebPreferences({
  665. embedder: event.sender,
  666. insecureParsedWebPreferences: parsedWebPreferences,
  667. secureOverrideWebPreferences
  668. });
  669. this._setNextChildWebPreferences(webPreferences);
  670. }
  671. });
  672. // Create a new browser window for "window.open"
  673. this.on('-add-new-contents' as any, (event: ElectronInternal.Event, webContents: Electron.WebContents, disposition: string,
  674. _userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
  675. referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
  676. const overriddenOptions = windowOpenOverriddenOptions || undefined;
  677. const outlivesOpener = windowOpenOutlivesOpenerOption;
  678. windowOpenOverriddenOptions = null;
  679. // false is the default
  680. windowOpenOutlivesOpenerOption = false;
  681. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  682. disposition !== 'background-tab')) {
  683. event.preventDefault();
  684. return;
  685. }
  686. openGuestWindow({
  687. event,
  688. embedder: event.sender,
  689. guest: webContents,
  690. overrideBrowserWindowOptions: overriddenOptions,
  691. disposition,
  692. referrer,
  693. postData,
  694. windowOpenArgs: {
  695. url,
  696. frameName,
  697. features: rawFeatures
  698. },
  699. outlivesOpener
  700. });
  701. });
  702. }
  703. this.on('login', (event, ...args) => {
  704. app.emit('login', event, this, ...args);
  705. });
  706. this.on('ready-to-show' as any, () => {
  707. const owner = this.getOwnerBrowserWindow();
  708. if (owner && !owner.isDestroyed()) {
  709. process.nextTick(() => {
  710. owner.emit('ready-to-show');
  711. });
  712. }
  713. });
  714. this.on('select-bluetooth-device', (event, devices, callback) => {
  715. if (this.listenerCount('select-bluetooth-device') === 1) {
  716. // Cancel it if there are no handlers
  717. event.preventDefault();
  718. callback('');
  719. }
  720. });
  721. const event = process._linkedBinding('electron_browser_event').createEmpty();
  722. app.emit('web-contents-created', event, this);
  723. // Properties
  724. Object.defineProperty(this, 'audioMuted', {
  725. get: () => this.isAudioMuted(),
  726. set: (muted) => this.setAudioMuted(muted)
  727. });
  728. Object.defineProperty(this, 'userAgent', {
  729. get: () => this.getUserAgent(),
  730. set: (agent) => this.setUserAgent(agent)
  731. });
  732. Object.defineProperty(this, 'zoomLevel', {
  733. get: () => this.getZoomLevel(),
  734. set: (level) => this.setZoomLevel(level)
  735. });
  736. Object.defineProperty(this, 'zoomFactor', {
  737. get: () => this.getZoomFactor(),
  738. set: (factor) => this.setZoomFactor(factor)
  739. });
  740. Object.defineProperty(this, 'frameRate', {
  741. get: () => this.getFrameRate(),
  742. set: (rate) => this.setFrameRate(rate)
  743. });
  744. Object.defineProperty(this, 'backgroundThrottling', {
  745. get: () => this.getBackgroundThrottling(),
  746. set: (allowed) => this.setBackgroundThrottling(allowed)
  747. });
  748. };
  749. // Public APIs.
  750. export function create (options = {}): Electron.WebContents {
  751. return new (WebContents as any)(options);
  752. }
  753. export function fromId (id: string) {
  754. return binding.fromId(id);
  755. }
  756. export function fromDevToolsTargetId (targetId: string) {
  757. return binding.fromDevToolsTargetId(targetId);
  758. }
  759. export function getFocusedWebContents () {
  760. let focused = null;
  761. for (const contents of binding.getAllWebContents()) {
  762. if (!contents.isFocused()) continue;
  763. if (focused == null) focused = contents;
  764. // Return webview web contents which may be embedded inside another
  765. // web contents that is also reporting as focused
  766. if (contents.getType() === 'webview') return contents;
  767. }
  768. return focused;
  769. }
  770. export function getAllWebContents () {
  771. return binding.getAllWebContents();
  772. }