web-contents.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. 'use strict';
  2. const { EventEmitter } = require('events');
  3. const electron = require('electron');
  4. const path = require('path');
  5. const url = require('url');
  6. const { app, ipcMain, session } = electron;
  7. const { internalWindowOpen } = require('@electron/internal/browser/guest-window-manager');
  8. const NavigationController = require('@electron/internal/browser/navigation-controller');
  9. const { ipcMainInternal } = require('@electron/internal/browser/ipc-main-internal');
  10. const ipcMainUtils = require('@electron/internal/browser/ipc-main-internal-utils');
  11. const { parseFeatures } = require('@electron/internal/common/parse-features-string');
  12. const { MessagePortMain } = require('@electron/internal/browser/message-port-main');
  13. // session is not used here, the purpose is to make sure session is initalized
  14. // before the webContents module.
  15. // eslint-disable-next-line
  16. session
  17. let nextId = 0;
  18. const getNextId = function () {
  19. return ++nextId;
  20. };
  21. // Stock page sizes
  22. const PDFPageSizes = {
  23. A5: {
  24. custom_display_name: 'A5',
  25. height_microns: 210000,
  26. name: 'ISO_A5',
  27. width_microns: 148000
  28. },
  29. A4: {
  30. custom_display_name: 'A4',
  31. height_microns: 297000,
  32. name: 'ISO_A4',
  33. is_default: 'true',
  34. width_microns: 210000
  35. },
  36. A3: {
  37. custom_display_name: 'A3',
  38. height_microns: 420000,
  39. name: 'ISO_A3',
  40. width_microns: 297000
  41. },
  42. Legal: {
  43. custom_display_name: 'Legal',
  44. height_microns: 355600,
  45. name: 'NA_LEGAL',
  46. width_microns: 215900
  47. },
  48. Letter: {
  49. custom_display_name: 'Letter',
  50. height_microns: 279400,
  51. name: 'NA_LETTER',
  52. width_microns: 215900
  53. },
  54. Tabloid: {
  55. height_microns: 431800,
  56. name: 'NA_LEDGER',
  57. width_microns: 279400,
  58. custom_display_name: 'Tabloid'
  59. }
  60. };
  61. // The minimum micron size Chromium accepts is that where:
  62. // Per printing/units.h:
  63. // * kMicronsPerInch - Length of an inch in 0.001mm unit.
  64. // * kPointsPerInch - Length of an inch in CSS's 1pt unit.
  65. //
  66. // Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1
  67. //
  68. // Practically, this means microns need to be > 352 microns.
  69. // We therefore need to verify this or it will silently fail.
  70. const isValidCustomPageSize = (width, height) => {
  71. return [width, height].every(x => x > 352);
  72. };
  73. // Default printing setting
  74. const defaultPrintingSetting = {
  75. // Customizable.
  76. pageRange: [],
  77. mediaSize: {},
  78. landscape: false,
  79. headerFooterEnabled: false,
  80. marginsType: 0,
  81. scaleFactor: 100,
  82. shouldPrintBackgrounds: false,
  83. shouldPrintSelectionOnly: false,
  84. // Non-customizable.
  85. printWithCloudPrint: false,
  86. printWithPrivet: false,
  87. printWithExtension: false,
  88. pagesPerSheet: 1,
  89. isFirstRequest: false,
  90. previewUIID: 0,
  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. };
  104. // JavaScript implementations of WebContents.
  105. const binding = process.electronBinding('web_contents');
  106. const { WebContents } = binding;
  107. Object.setPrototypeOf(NavigationController.prototype, EventEmitter.prototype);
  108. Object.setPrototypeOf(WebContents.prototype, NavigationController.prototype);
  109. // WebContents::send(channel, args..)
  110. // WebContents::sendToAll(channel, args..)
  111. WebContents.prototype.send = function (channel, ...args) {
  112. if (typeof channel !== 'string') {
  113. throw new Error('Missing required channel argument');
  114. }
  115. const internal = false;
  116. const sendToAll = false;
  117. return this._send(internal, sendToAll, channel, args);
  118. };
  119. WebContents.prototype.postMessage = function (...args) {
  120. if (Array.isArray(args[2])) {
  121. args[2] = args[2].map(o => o instanceof MessagePortMain ? o._internalPort : o);
  122. }
  123. this._postMessage(...args);
  124. };
  125. WebContents.prototype.sendToAll = function (channel, ...args) {
  126. if (typeof channel !== 'string') {
  127. throw new Error('Missing required channel argument');
  128. }
  129. const internal = false;
  130. const sendToAll = true;
  131. return this._send(internal, sendToAll, channel, args);
  132. };
  133. WebContents.prototype._sendInternal = function (channel, ...args) {
  134. if (typeof channel !== 'string') {
  135. throw new Error('Missing required channel argument');
  136. }
  137. const internal = true;
  138. const sendToAll = false;
  139. return this._send(internal, sendToAll, channel, args);
  140. };
  141. WebContents.prototype._sendInternalToAll = function (channel, ...args) {
  142. if (typeof channel !== 'string') {
  143. throw new Error('Missing required channel argument');
  144. }
  145. const internal = true;
  146. const sendToAll = true;
  147. return this._send(internal, sendToAll, channel, args);
  148. };
  149. WebContents.prototype.sendToFrame = function (frame, channel, ...args) {
  150. if (typeof channel !== 'string') {
  151. throw new Error('Missing required channel argument');
  152. } else if (!(typeof frame === 'number' || Array.isArray(frame))) {
  153. throw new Error('Missing required frame argument (must be number or array)');
  154. }
  155. const internal = false;
  156. const sendToAll = false;
  157. return this._sendToFrame(internal, sendToAll, frame, channel, args);
  158. };
  159. WebContents.prototype._sendToFrameInternal = function (frame, channel, ...args) {
  160. if (typeof channel !== 'string') {
  161. throw new Error('Missing required channel argument');
  162. } else if (!(typeof frame === 'number' || Array.isArray(frame))) {
  163. throw new Error('Missing required frame argument (must be number or array)');
  164. }
  165. const internal = true;
  166. const sendToAll = false;
  167. return this._sendToFrame(internal, sendToAll, frame, channel, args);
  168. };
  169. // Following methods are mapped to webFrame.
  170. const webFrameMethods = [
  171. 'insertCSS',
  172. 'insertText',
  173. 'removeInsertedCSS',
  174. 'setVisualZoomLevelLimits'
  175. ];
  176. for (const method of webFrameMethods) {
  177. WebContents.prototype[method] = function (...args) {
  178. return ipcMainUtils.invokeInWebContents(this, false, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, ...args);
  179. };
  180. }
  181. const waitTillCanExecuteJavaScript = async (webContents) => {
  182. if (webContents.getURL() && !webContents.isLoadingMainFrame()) return;
  183. return new Promise((resolve) => {
  184. webContents.once('did-stop-loading', () => {
  185. resolve();
  186. });
  187. });
  188. };
  189. // Make sure WebContents::executeJavaScript would run the code only when the
  190. // WebContents has been loaded.
  191. WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) {
  192. await waitTillCanExecuteJavaScript(this);
  193. return ipcMainUtils.invokeInWebContents(this, false, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', 'executeJavaScript', code, hasUserGesture);
  194. };
  195. WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (code, hasUserGesture) {
  196. await waitTillCanExecuteJavaScript(this);
  197. return ipcMainUtils.invokeInWebContents(this, false, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', 'executeJavaScriptInIsolatedWorld', code, hasUserGesture);
  198. };
  199. // Translate the options of printToPDF.
  200. let pendingPromise;
  201. WebContents.prototype.printToPDF = async function (options) {
  202. const printSettings = {
  203. ...defaultPrintingSetting,
  204. requestID: getNextId()
  205. };
  206. if (options.landscape !== undefined) {
  207. if (typeof options.landscape !== 'boolean') {
  208. const error = new Error('landscape must be a Boolean');
  209. return Promise.reject(error);
  210. }
  211. printSettings.landscape = options.landscape;
  212. }
  213. if (options.scaleFactor !== undefined) {
  214. if (typeof options.scaleFactor !== 'number') {
  215. const error = new Error('scaleFactor must be a Number');
  216. return Promise.reject(error);
  217. }
  218. printSettings.scaleFactor = options.scaleFactor;
  219. }
  220. if (options.marginsType !== undefined) {
  221. if (typeof options.marginsType !== 'number') {
  222. const error = new Error('marginsType must be a Number');
  223. return Promise.reject(error);
  224. }
  225. printSettings.marginsType = options.marginsType;
  226. }
  227. if (options.printSelectionOnly !== undefined) {
  228. if (typeof options.printSelectionOnly !== 'boolean') {
  229. const error = new Error('printSelectionOnly must be a Boolean');
  230. return Promise.reject(error);
  231. }
  232. printSettings.shouldPrintSelectionOnly = options.printSelectionOnly;
  233. }
  234. if (options.printBackground !== undefined) {
  235. if (typeof options.printBackground !== 'boolean') {
  236. const error = new Error('printBackground must be a Boolean');
  237. return Promise.reject(error);
  238. }
  239. printSettings.shouldPrintBackgrounds = options.printBackground;
  240. }
  241. if (options.pageRanges !== undefined) {
  242. const pageRanges = options.pageRanges;
  243. if (!Object.prototype.hasOwnProperty.call(pageRanges, 'from') || !Object.prototype.hasOwnProperty.call(pageRanges, 'to')) {
  244. const error = new Error('pageRanges must be an Object with \'from\' and \'to\' properties');
  245. return Promise.reject(error);
  246. }
  247. if (typeof pageRanges.from !== 'number') {
  248. const error = new Error('pageRanges.from must be a Number');
  249. return Promise.reject(error);
  250. }
  251. if (typeof pageRanges.to !== 'number') {
  252. const error = new Error('pageRanges.to must be a Number');
  253. return Promise.reject(error);
  254. }
  255. // Chromium uses 1-based page ranges, so increment each by 1.
  256. printSettings.pageRange = [{
  257. from: pageRanges.from + 1,
  258. to: pageRanges.to + 1
  259. }];
  260. }
  261. if (options.headerFooter !== undefined) {
  262. const headerFooter = options.headerFooter;
  263. printSettings.headerFooterEnabled = true;
  264. if (typeof headerFooter === 'object') {
  265. if (!headerFooter.url || !headerFooter.title) {
  266. const error = new Error('url and title properties are required for headerFooter');
  267. return Promise.reject(error);
  268. }
  269. if (typeof headerFooter.title !== 'string') {
  270. const error = new Error('headerFooter.title must be a String');
  271. return Promise.reject(error);
  272. }
  273. printSettings.title = headerFooter.title;
  274. if (typeof headerFooter.url !== 'string') {
  275. const error = new Error('headerFooter.url must be a String');
  276. return Promise.reject(error);
  277. }
  278. printSettings.url = headerFooter.url;
  279. } else {
  280. const error = new Error('headerFooter must be an Object');
  281. return Promise.reject(error);
  282. }
  283. }
  284. // Optionally set size for PDF.
  285. if (options.pageSize !== undefined) {
  286. const pageSize = options.pageSize;
  287. if (typeof pageSize === 'object') {
  288. if (!pageSize.height || !pageSize.width) {
  289. const error = new Error('height and width properties are required for pageSize');
  290. return Promise.reject(error);
  291. }
  292. // Dimensions in Microns - 1 meter = 10^6 microns
  293. const height = Math.ceil(pageSize.height);
  294. const width = Math.ceil(pageSize.width);
  295. if (!isValidCustomPageSize(width, height)) {
  296. const error = new Error('height and width properties must be minimum 352 microns.');
  297. return Promise.reject(error);
  298. }
  299. printSettings.mediaSize = {
  300. name: 'CUSTOM',
  301. custom_display_name: 'Custom',
  302. height_microns: height,
  303. width_microns: width
  304. };
  305. } else if (PDFPageSizes[pageSize]) {
  306. printSettings.mediaSize = PDFPageSizes[pageSize];
  307. } else {
  308. const error = new Error(`Unsupported pageSize: ${pageSize}`);
  309. return Promise.reject(error);
  310. }
  311. } else {
  312. printSettings.mediaSize = PDFPageSizes.A4;
  313. }
  314. // Chromium expects this in a 0-100 range number, not as float
  315. printSettings.scaleFactor = Math.ceil(printSettings.scaleFactor) % 100;
  316. // PrinterType enum from //printing/print_job_constants.h
  317. printSettings.printerType = 2;
  318. if (this._printToPDF) {
  319. if (pendingPromise) {
  320. pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings));
  321. } else {
  322. pendingPromise = this._printToPDF(printSettings);
  323. }
  324. return pendingPromise;
  325. } else {
  326. const error = new Error('Printing feature is disabled');
  327. return Promise.reject(error);
  328. }
  329. };
  330. WebContents.prototype.print = function (options = {}, callback) {
  331. // TODO(codebytere): deduplicate argument sanitization by moving rest of
  332. // print param logic into new file shared between printToPDF and print
  333. if (typeof options === 'object') {
  334. // Optionally set size for PDF.
  335. if (options.pageSize !== undefined) {
  336. const pageSize = options.pageSize;
  337. if (typeof pageSize === 'object') {
  338. if (!pageSize.height || !pageSize.width) {
  339. throw new Error('height and width properties are required for pageSize');
  340. }
  341. // Dimensions in Microns - 1 meter = 10^6 microns
  342. const height = Math.ceil(pageSize.height);
  343. const width = Math.ceil(pageSize.width);
  344. if (!isValidCustomPageSize(width, height)) {
  345. throw new Error('height and width properties must be minimum 352 microns.');
  346. }
  347. options.mediaSize = {
  348. name: 'CUSTOM',
  349. custom_display_name: 'Custom',
  350. height_microns: height,
  351. width_microns: width
  352. };
  353. } else if (PDFPageSizes[pageSize]) {
  354. options.mediaSize = PDFPageSizes[pageSize];
  355. } else {
  356. throw new Error(`Unsupported pageSize: ${pageSize}`);
  357. }
  358. }
  359. }
  360. if (this._print) {
  361. if (callback) {
  362. this._print(options, callback);
  363. } else {
  364. this._print(options);
  365. }
  366. } else {
  367. console.error('Error: Printing feature is disabled.');
  368. }
  369. };
  370. WebContents.prototype.getPrinters = function () {
  371. if (this._getPrinters) {
  372. return this._getPrinters();
  373. } else {
  374. console.error('Error: Printing feature is disabled.');
  375. return [];
  376. }
  377. };
  378. WebContents.prototype.loadFile = function (filePath, options = {}) {
  379. if (typeof filePath !== 'string') {
  380. throw new Error('Must pass filePath as a string');
  381. }
  382. const { query, search, hash } = options;
  383. return this.loadURL(url.format({
  384. protocol: 'file',
  385. slashes: true,
  386. pathname: path.resolve(app.getAppPath(), filePath),
  387. query,
  388. search,
  389. hash
  390. }));
  391. };
  392. const addReplyToEvent = (event) => {
  393. const { processId, frameId } = event;
  394. event.reply = (...args) => {
  395. event.sender.sendToFrame([processId, frameId], ...args);
  396. };
  397. };
  398. const addReplyInternalToEvent = (event) => {
  399. Object.defineProperty(event, '_replyInternal', {
  400. configurable: false,
  401. enumerable: false,
  402. value: (...args) => {
  403. event.sender._sendToFrameInternal(event.frameId, ...args);
  404. }
  405. });
  406. };
  407. const addReturnValueToEvent = (event) => {
  408. Object.defineProperty(event, 'returnValue', {
  409. set: (value) => event.sendReply([value]),
  410. get: () => {}
  411. });
  412. };
  413. const loggingEnabled = () => {
  414. return process.env.ELECTRON_ENABLE_LOGGING || app.commandLine.hasSwitch('enable-logging');
  415. };
  416. // Add JavaScript wrappers for WebContents class.
  417. WebContents.prototype._init = function () {
  418. // The navigation controller.
  419. NavigationController.call(this, this);
  420. // Every remote callback from renderer process would add a listener to the
  421. // render-view-deleted event, so ignore the listeners warning.
  422. this.setMaxListeners(0);
  423. // Dispatch IPC messages to the ipc module.
  424. this.on('-ipc-message', function (event, internal, channel, args) {
  425. if (internal) {
  426. addReplyInternalToEvent(event);
  427. ipcMainInternal.emit(channel, event, ...args);
  428. } else {
  429. addReplyToEvent(event);
  430. this.emit('ipc-message', event, channel, ...args);
  431. ipcMain.emit(channel, event, ...args);
  432. }
  433. });
  434. this.on('-ipc-invoke', function (event, internal, channel, args) {
  435. event._reply = (result) => event.sendReply({ result });
  436. event._throw = (error) => {
  437. console.error(`Error occurred in handler for '${channel}':`, error);
  438. event.sendReply({ error: error.toString() });
  439. };
  440. const target = internal ? ipcMainInternal : ipcMain;
  441. if (target._invokeHandlers.has(channel)) {
  442. target._invokeHandlers.get(channel)(event, ...args);
  443. } else {
  444. event._throw(`No handler registered for '${channel}'`);
  445. }
  446. });
  447. this.on('-ipc-message-sync', function (event, internal, channel, args) {
  448. addReturnValueToEvent(event);
  449. if (internal) {
  450. addReplyInternalToEvent(event);
  451. ipcMainInternal.emit(channel, event, ...args);
  452. } else {
  453. addReplyToEvent(event);
  454. this.emit('ipc-message-sync', event, channel, ...args);
  455. ipcMain.emit(channel, event, ...args);
  456. }
  457. });
  458. this.on('-ipc-ports', function (event, internal, channel, message, ports) {
  459. event.ports = ports.map(p => new MessagePortMain(p));
  460. ipcMain.emit(channel, event, message);
  461. });
  462. // Handle context menu action request from pepper plugin.
  463. this.on('pepper-context-menu', function (event, params, callback) {
  464. // Access Menu via electron.Menu to prevent circular require.
  465. const menu = electron.Menu.buildFromTemplate(params.menu);
  466. menu.popup({
  467. window: event.sender.getOwnerBrowserWindow(),
  468. x: params.x,
  469. y: params.y,
  470. callback
  471. });
  472. });
  473. this.on('crashed', (event, ...args) => {
  474. app.emit('renderer-process-crashed', event, this, ...args);
  475. });
  476. this.on('render-process-gone', (event, details) => {
  477. app.emit('render-process-gone', event, this, details);
  478. // Log out a hint to help users better debug renderer crashes.
  479. if (loggingEnabled()) {
  480. console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`);
  481. }
  482. });
  483. // The devtools requests the webContents to reload.
  484. this.on('devtools-reload-page', function () {
  485. this.reload();
  486. });
  487. if (this.getType() !== 'remote') {
  488. // Make new windows requested by links behave like "window.open".
  489. this.on('-new-window', (event, url, frameName, disposition,
  490. rawFeatures, referrer, postData) => {
  491. const { options, webPreferences, additionalFeatures } = parseFeatures(rawFeatures);
  492. const mergedOptions = {
  493. show: true,
  494. width: 800,
  495. height: 600,
  496. title: frameName,
  497. webPreferences,
  498. ...options
  499. };
  500. internalWindowOpen(event, url, referrer, frameName, disposition, mergedOptions, additionalFeatures, postData);
  501. });
  502. // Create a new browser window for the native implementation of
  503. // "window.open", used in sandbox and nativeWindowOpen mode.
  504. this.on('-add-new-contents', (event, webContents, disposition,
  505. userGesture, left, top, width, height, url, frameName,
  506. referrer, rawFeatures, postData) => {
  507. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  508. disposition !== 'background-tab')) {
  509. event.preventDefault();
  510. return;
  511. }
  512. const { options, webPreferences, additionalFeatures } = parseFeatures(rawFeatures);
  513. const mergedOptions = {
  514. show: true,
  515. width: 800,
  516. height: 600,
  517. webContents,
  518. webPreferences,
  519. ...options
  520. };
  521. internalWindowOpen(event, url, referrer, frameName, disposition, mergedOptions, additionalFeatures, postData);
  522. });
  523. const prefs = this.getWebPreferences() || {};
  524. if (prefs.webviewTag && prefs.contextIsolation) {
  525. electron.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');
  526. }
  527. }
  528. this.on('login', (event, ...args) => {
  529. app.emit('login', event, this, ...args);
  530. });
  531. this.on('ready-to-show', () => {
  532. const owner = this.getOwnerBrowserWindow();
  533. if (owner && !owner.isDestroyed()) {
  534. process.nextTick(() => {
  535. owner.emit('ready-to-show');
  536. });
  537. }
  538. });
  539. const event = process.electronBinding('event').createEmpty();
  540. app.emit('web-contents-created', event, this);
  541. // Properties
  542. Object.defineProperty(this, 'audioMuted', {
  543. get: () => this.isAudioMuted(),
  544. set: (muted) => this.setAudioMuted(muted)
  545. });
  546. Object.defineProperty(this, 'userAgent', {
  547. get: () => this.getUserAgent(),
  548. set: (agent) => this.setUserAgent(agent)
  549. });
  550. Object.defineProperty(this, 'zoomLevel', {
  551. get: () => this.getZoomLevel(),
  552. set: (level) => this.setZoomLevel(level)
  553. });
  554. Object.defineProperty(this, 'zoomFactor', {
  555. get: () => this.getZoomFactor(),
  556. set: (factor) => this.setZoomFactor(factor)
  557. });
  558. Object.defineProperty(this, 'frameRate', {
  559. get: () => this.getFrameRate(),
  560. set: (rate) => this.setFrameRate(rate)
  561. });
  562. Object.defineProperty(this, 'backgroundThrottling', {
  563. get: () => this.getBackgroundThrottling(),
  564. set: (allowed) => this.setBackgroundThrottling(allowed)
  565. });
  566. };
  567. // Public APIs.
  568. module.exports = {
  569. create (options = {}) {
  570. return binding.create(options);
  571. },
  572. fromId (id) {
  573. return binding.fromId(id);
  574. },
  575. getFocusedWebContents () {
  576. let focused = null;
  577. for (const contents of binding.getAllWebContents()) {
  578. if (!contents.isFocused()) continue;
  579. if (focused == null) focused = contents;
  580. // Return webview web contents which may be embedded inside another
  581. // web contents that is also reporting as focused
  582. if (contents.getType() === 'webview') return contents;
  583. }
  584. return focused;
  585. },
  586. getAllWebContents () {
  587. return binding.getAllWebContents();
  588. }
  589. };