web-contents.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. import { app, ipcMain, session, deprecate, 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 { NavigationController } from '@electron/internal/browser/navigation-controller';
  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.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'allow'} | {action: 'deny', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions})) {
  367. this._windowOpenHandler = handler;
  368. };
  369. WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): BrowserWindowConstructorOptions | null {
  370. if (!this._windowOpenHandler) {
  371. return null;
  372. }
  373. const response = this._windowOpenHandler(details);
  374. if (typeof response !== 'object') {
  375. event.preventDefault();
  376. console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`);
  377. return null;
  378. }
  379. if (response === null) {
  380. event.preventDefault();
  381. console.error('The window open handler response must be an object, but was instead null.');
  382. return null;
  383. }
  384. if (response.action === 'deny') {
  385. event.preventDefault();
  386. return null;
  387. } else if (response.action === 'allow') {
  388. if (typeof response.overrideBrowserWindowOptions === 'object' && response.overrideBrowserWindowOptions !== null) {
  389. return response.overrideBrowserWindowOptions;
  390. } else {
  391. return {};
  392. }
  393. } else {
  394. event.preventDefault();
  395. console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.');
  396. return null;
  397. }
  398. };
  399. const addReplyToEvent = (event: Electron.IpcMainEvent) => {
  400. const { processId, frameId } = event;
  401. event.reply = (channel: string, ...args: any[]) => {
  402. event.sender.sendToFrame([processId, frameId], channel, ...args);
  403. };
  404. };
  405. const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
  406. const { processId, frameId } = event;
  407. Object.defineProperty(event, 'senderFrame', {
  408. get: () => webFrameMain.fromId(processId, frameId)
  409. });
  410. };
  411. const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
  412. Object.defineProperty(event, 'returnValue', {
  413. set: (value) => event.sendReply(value),
  414. get: () => {}
  415. });
  416. };
  417. const commandLine = process._linkedBinding('electron_common_command_line');
  418. const environment = process._linkedBinding('electron_common_environment');
  419. const loggingEnabled = () => {
  420. return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging');
  421. };
  422. // Add JavaScript wrappers for WebContents class.
  423. WebContents.prototype._init = function () {
  424. // The navigation controller.
  425. const navigationController = new NavigationController(this);
  426. this.loadURL = navigationController.loadURL.bind(navigationController);
  427. this.getURL = navigationController.getURL.bind(navigationController);
  428. this.stop = navigationController.stop.bind(navigationController);
  429. this.reload = navigationController.reload.bind(navigationController);
  430. this.reloadIgnoringCache = navigationController.reloadIgnoringCache.bind(navigationController);
  431. this.canGoBack = navigationController.canGoBack.bind(navigationController);
  432. this.canGoForward = navigationController.canGoForward.bind(navigationController);
  433. this.canGoToIndex = navigationController.canGoToIndex.bind(navigationController);
  434. this.canGoToOffset = navigationController.canGoToOffset.bind(navigationController);
  435. this.clearHistory = navigationController.clearHistory.bind(navigationController);
  436. this.goBack = navigationController.goBack.bind(navigationController);
  437. this.goForward = navigationController.goForward.bind(navigationController);
  438. this.goToIndex = navigationController.goToIndex.bind(navigationController);
  439. this.goToOffset = navigationController.goToOffset.bind(navigationController);
  440. this.getActiveIndex = navigationController.getActiveIndex.bind(navigationController);
  441. this.length = navigationController.length.bind(navigationController);
  442. // Read off the ID at construction time, so that it's accessible even after
  443. // the underlying C++ WebContents is destroyed.
  444. const id = this.id;
  445. Object.defineProperty(this, 'id', {
  446. value: id,
  447. writable: false
  448. });
  449. this._windowOpenHandler = null;
  450. // Every remote callback from renderer process would add a listener to the
  451. // render-view-deleted event, so ignore the listeners warning.
  452. this.setMaxListeners(0);
  453. // Dispatch IPC messages to the ipc module.
  454. this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
  455. addSenderFrameToEvent(event);
  456. if (internal) {
  457. ipcMainInternal.emit(channel, event, ...args);
  458. } else {
  459. addReplyToEvent(event);
  460. this.emit('ipc-message', event, channel, ...args);
  461. ipcMain.emit(channel, event, ...args);
  462. }
  463. });
  464. this.on('-ipc-invoke' as any, function (event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
  465. addSenderFrameToEvent(event);
  466. event._reply = (result: any) => event.sendReply({ result });
  467. event._throw = (error: Error) => {
  468. console.error(`Error occurred in handler for '${channel}':`, error);
  469. event.sendReply({ error: error.toString() });
  470. };
  471. const target = internal ? ipcMainInternal : ipcMain;
  472. if ((target as any)._invokeHandlers.has(channel)) {
  473. (target as any)._invokeHandlers.get(channel)(event, ...args);
  474. } else {
  475. event._throw(`No handler registered for '${channel}'`);
  476. }
  477. });
  478. this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
  479. addSenderFrameToEvent(event);
  480. addReturnValueToEvent(event);
  481. if (internal) {
  482. ipcMainInternal.emit(channel, event, ...args);
  483. } else {
  484. addReplyToEvent(event);
  485. if (this.listenerCount('ipc-message-sync') === 0 && ipcMain.listenerCount(channel) === 0) {
  486. console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`);
  487. }
  488. this.emit('ipc-message-sync', event, channel, ...args);
  489. ipcMain.emit(channel, event, ...args);
  490. }
  491. });
  492. this.on('-ipc-ports' as any, function (event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
  493. event.ports = ports.map(p => new MessagePortMain(p));
  494. ipcMain.emit(channel, event, message);
  495. });
  496. this.on('crashed', (event, ...args) => {
  497. app.emit('renderer-process-crashed', event, this, ...args);
  498. });
  499. this.on('render-process-gone', (event, details) => {
  500. app.emit('render-process-gone', event, this, details);
  501. // Log out a hint to help users better debug renderer crashes.
  502. if (loggingEnabled()) {
  503. console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`);
  504. }
  505. });
  506. // The devtools requests the webContents to reload.
  507. this.on('devtools-reload-page', function (this: Electron.WebContents) {
  508. this.reload();
  509. });
  510. if (this.getType() !== 'remote') {
  511. // Make new windows requested by links behave like "window.open".
  512. this.on('-new-window' as any, (event: ElectronInternal.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
  513. rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
  514. const postBody = postData ? {
  515. data: postData,
  516. ...parseContentTypeFormat(postData)
  517. } : undefined;
  518. const details: Electron.HandlerDetails = {
  519. url,
  520. frameName,
  521. features: rawFeatures,
  522. referrer,
  523. postBody,
  524. disposition
  525. };
  526. const options = this._callWindowOpenHandler(event, details);
  527. if (!event.defaultPrevented) {
  528. openGuestWindow({
  529. event,
  530. embedder: event.sender,
  531. disposition,
  532. referrer,
  533. postData,
  534. overrideBrowserWindowOptions: options || {},
  535. windowOpenArgs: details
  536. });
  537. }
  538. });
  539. let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
  540. 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) => {
  541. const postBody = postData ? {
  542. data: postData,
  543. ...parseContentTypeFormat(postData)
  544. } : undefined;
  545. const details: Electron.HandlerDetails = {
  546. url,
  547. frameName,
  548. features: rawFeatures,
  549. disposition,
  550. referrer,
  551. postBody
  552. };
  553. windowOpenOverriddenOptions = this._callWindowOpenHandler(event, details);
  554. if (!event.defaultPrevented) {
  555. const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
  556. // Allow setting of backgroundColor as a webPreference even though
  557. // it's technically a BrowserWindowConstructorOptions option because
  558. // we need to access it in the renderer at init time.
  559. backgroundColor: windowOpenOverriddenOptions.backgroundColor,
  560. transparent: windowOpenOverriddenOptions.transparent,
  561. ...windowOpenOverriddenOptions.webPreferences
  562. } : undefined;
  563. this._setNextChildWebPreferences(
  564. makeWebPreferences({ embedder: event.sender, secureOverrideWebPreferences })
  565. );
  566. }
  567. });
  568. // Create a new browser window for the native implementation of
  569. // "window.open", used in sandbox and nativeWindowOpen mode.
  570. this.on('-add-new-contents' as any, (event: ElectronInternal.Event, webContents: Electron.WebContents, disposition: string,
  571. _userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
  572. referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
  573. const overriddenOptions = windowOpenOverriddenOptions || undefined;
  574. windowOpenOverriddenOptions = null;
  575. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  576. disposition !== 'background-tab')) {
  577. event.preventDefault();
  578. return;
  579. }
  580. openGuestWindow({
  581. event,
  582. embedder: event.sender,
  583. guest: webContents,
  584. overrideBrowserWindowOptions: overriddenOptions,
  585. disposition,
  586. referrer,
  587. postData,
  588. windowOpenArgs: {
  589. url,
  590. frameName,
  591. features: rawFeatures
  592. }
  593. });
  594. });
  595. const prefs = this.getWebPreferences() || {};
  596. if (prefs.webviewTag && prefs.contextIsolation) {
  597. deprecate.log('Security Warning: A WebContents was just created with both webviewTag and contextIsolation enabled. This combination is fundamentally less secure and effectively bypasses the protections of contextIsolation. We strongly recommend you move away from webviews to OOPIF or BrowserView in order for your app to be more secure');
  598. }
  599. }
  600. this.on('login', (event, ...args) => {
  601. app.emit('login', event, this, ...args);
  602. });
  603. this.on('ready-to-show' as any, () => {
  604. const owner = this.getOwnerBrowserWindow();
  605. if (owner && !owner.isDestroyed()) {
  606. process.nextTick(() => {
  607. owner.emit('ready-to-show');
  608. });
  609. }
  610. });
  611. this.on('select-bluetooth-device', (event, devices, callback) => {
  612. if (this.listenerCount('select-bluetooth-device') === 1) {
  613. // Cancel it if there are no handlers
  614. event.preventDefault();
  615. callback('');
  616. }
  617. });
  618. const event = process._linkedBinding('electron_browser_event').createEmpty();
  619. app.emit('web-contents-created', event, this);
  620. // Properties
  621. Object.defineProperty(this, 'audioMuted', {
  622. get: () => this.isAudioMuted(),
  623. set: (muted) => this.setAudioMuted(muted)
  624. });
  625. Object.defineProperty(this, 'userAgent', {
  626. get: () => this.getUserAgent(),
  627. set: (agent) => this.setUserAgent(agent)
  628. });
  629. Object.defineProperty(this, 'zoomLevel', {
  630. get: () => this.getZoomLevel(),
  631. set: (level) => this.setZoomLevel(level)
  632. });
  633. Object.defineProperty(this, 'zoomFactor', {
  634. get: () => this.getZoomFactor(),
  635. set: (factor) => this.setZoomFactor(factor)
  636. });
  637. Object.defineProperty(this, 'frameRate', {
  638. get: () => this.getFrameRate(),
  639. set: (rate) => this.setFrameRate(rate)
  640. });
  641. Object.defineProperty(this, 'backgroundThrottling', {
  642. get: () => this.getBackgroundThrottling(),
  643. set: (allowed) => this.setBackgroundThrottling(allowed)
  644. });
  645. };
  646. // Public APIs.
  647. export function create (options = {}): Electron.WebContents {
  648. return new (WebContents as any)(options);
  649. }
  650. export function fromId (id: string) {
  651. return binding.fromId(id);
  652. }
  653. export function fromDevToolsTargetId (targetId: string) {
  654. return binding.fromDevToolsTargetId(targetId);
  655. }
  656. export function getFocusedWebContents () {
  657. let focused = null;
  658. for (const contents of binding.getAllWebContents()) {
  659. if (!contents.isFocused()) continue;
  660. if (focused == null) focused = contents;
  661. // Return webview web contents which may be embedded inside another
  662. // web contents that is also reporting as focused
  663. if (contents.getType() === 'webview') return contents;
  664. }
  665. return focused;
  666. }
  667. export function getAllWebContents () {
  668. return binding.getAllWebContents();
  669. }