web-contents.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. 'use strict';
  2. const features = process.electronBinding('features');
  3. const { EventEmitter } = require('events');
  4. const electron = require('electron');
  5. const path = require('path');
  6. const url = require('url');
  7. const { app, ipcMain, session, deprecate } = electron;
  8. const { internalWindowOpen } = require('@electron/internal/browser/guest-window-manager');
  9. const NavigationController = require('@electron/internal/browser/navigation-controller');
  10. const { ipcMainInternal } = require('@electron/internal/browser/ipc-main-internal');
  11. const ipcMainUtils = require('@electron/internal/browser/ipc-main-internal-utils');
  12. const errorUtils = require('@electron/internal/common/error-utils');
  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. // Default printing setting
  62. const defaultPrintingSetting = {
  63. pageRage: [],
  64. mediaSize: {},
  65. landscape: false,
  66. color: 2,
  67. headerFooterEnabled: false,
  68. marginsType: 0,
  69. isFirstRequest: false,
  70. previewUIID: 0,
  71. previewModifiable: true,
  72. printToPDF: true,
  73. printWithCloudPrint: false,
  74. printWithPrivet: false,
  75. printWithExtension: false,
  76. pagesPerSheet: 1,
  77. deviceName: 'Save as PDF',
  78. generateDraftData: true,
  79. fitToPageEnabled: false,
  80. scaleFactor: 1,
  81. dpiHorizontal: 72,
  82. dpiVertical: 72,
  83. rasterizePDF: false,
  84. duplex: 0,
  85. copies: 1,
  86. collate: true,
  87. shouldPrintBackgrounds: false,
  88. shouldPrintSelectionOnly: false
  89. };
  90. // JavaScript implementations of WebContents.
  91. const binding = process.electronBinding('web_contents');
  92. const { WebContents } = binding;
  93. Object.setPrototypeOf(NavigationController.prototype, EventEmitter.prototype);
  94. Object.setPrototypeOf(WebContents.prototype, NavigationController.prototype);
  95. // WebContents::send(channel, args..)
  96. // WebContents::sendToAll(channel, args..)
  97. WebContents.prototype.send = function (channel, ...args) {
  98. if (typeof channel !== 'string') {
  99. throw new Error('Missing required channel argument');
  100. }
  101. const internal = false;
  102. const sendToAll = false;
  103. return this._send(internal, sendToAll, channel, args);
  104. };
  105. WebContents.prototype.sendToAll = function (channel, ...args) {
  106. if (typeof channel !== 'string') {
  107. throw new Error('Missing required channel argument');
  108. }
  109. const internal = false;
  110. const sendToAll = true;
  111. return this._send(internal, sendToAll, channel, args);
  112. };
  113. WebContents.prototype._sendInternal = function (channel, ...args) {
  114. if (typeof channel !== 'string') {
  115. throw new Error('Missing required channel argument');
  116. }
  117. const internal = true;
  118. const sendToAll = false;
  119. return this._send(internal, sendToAll, channel, args);
  120. };
  121. WebContents.prototype._sendInternalToAll = function (channel, ...args) {
  122. if (typeof channel !== 'string') {
  123. throw new Error('Missing required channel argument');
  124. }
  125. const internal = true;
  126. const sendToAll = true;
  127. return this._send(internal, sendToAll, channel, args);
  128. };
  129. WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
  130. if (typeof channel !== 'string') {
  131. throw new Error('Missing required channel argument');
  132. } else if (typeof frameId !== 'number') {
  133. throw new Error('Missing required frameId argument');
  134. }
  135. const internal = false;
  136. const sendToAll = false;
  137. return this._sendToFrame(internal, sendToAll, frameId, channel, args);
  138. };
  139. WebContents.prototype._sendToFrameInternal = function (frameId, channel, ...args) {
  140. if (typeof channel !== 'string') {
  141. throw new Error('Missing required channel argument');
  142. } else if (typeof frameId !== 'number') {
  143. throw new Error('Missing required frameId argument');
  144. }
  145. const internal = true;
  146. const sendToAll = false;
  147. return this._sendToFrame(internal, sendToAll, frameId, channel, args);
  148. };
  149. // Following methods are mapped to webFrame.
  150. const webFrameMethods = [
  151. 'insertCSS',
  152. 'insertText',
  153. 'removeInsertedCSS',
  154. 'setLayoutZoomLevelLimits',
  155. 'setVisualZoomLevelLimits'
  156. ];
  157. for (const method of webFrameMethods) {
  158. WebContents.prototype[method] = function (...args) {
  159. return ipcMainUtils.invokeInWebContents(this, false, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, ...args);
  160. };
  161. }
  162. const executeJavaScript = (contents, code, hasUserGesture) => {
  163. return ipcMainUtils.invokeInWebContents(contents, false, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', 'executeJavaScript', code, hasUserGesture);
  164. };
  165. // Make sure WebContents::executeJavaScript would run the code only when the
  166. // WebContents has been loaded.
  167. WebContents.prototype.executeJavaScript = function (code, hasUserGesture) {
  168. if (this.getURL() && !this.isLoadingMainFrame()) {
  169. return executeJavaScript(this, code, hasUserGesture);
  170. } else {
  171. return new Promise((resolve, reject) => {
  172. this.once('did-stop-loading', () => {
  173. executeJavaScript(this, code, hasUserGesture).then(resolve, reject);
  174. });
  175. });
  176. }
  177. };
  178. // Translate the options of printToPDF.
  179. WebContents.prototype.printToPDF = function (options) {
  180. const printingSetting = {
  181. ...defaultPrintingSetting,
  182. requestID: getNextId()
  183. };
  184. if (options.landscape) {
  185. printingSetting.landscape = options.landscape;
  186. }
  187. if (options.marginsType) {
  188. printingSetting.marginsType = options.marginsType;
  189. }
  190. if (options.printSelectionOnly) {
  191. printingSetting.shouldPrintSelectionOnly = options.printSelectionOnly;
  192. }
  193. if (options.printBackground) {
  194. printingSetting.shouldPrintBackgrounds = options.printBackground;
  195. }
  196. if (options.pageSize) {
  197. const pageSize = options.pageSize;
  198. if (typeof pageSize === 'object') {
  199. if (!pageSize.height || !pageSize.width) {
  200. return Promise.reject(new Error('Must define height and width for pageSize'));
  201. }
  202. // Dimensions in Microns
  203. // 1 meter = 10^6 microns
  204. printingSetting.mediaSize = {
  205. name: 'CUSTOM',
  206. custom_display_name: 'Custom',
  207. height_microns: Math.ceil(pageSize.height),
  208. width_microns: Math.ceil(pageSize.width)
  209. };
  210. } else if (PDFPageSizes[pageSize]) {
  211. printingSetting.mediaSize = PDFPageSizes[pageSize];
  212. } else {
  213. return Promise.reject(new Error(`Does not support pageSize with ${pageSize}`));
  214. }
  215. } else {
  216. printingSetting.mediaSize = PDFPageSizes['A4'];
  217. }
  218. // Chromium expects this in a 0-100 range number, not as float
  219. printingSetting.scaleFactor *= 100;
  220. if (features.isPrintingEnabled()) {
  221. return this._printToPDF(printingSetting);
  222. } else {
  223. return Promise.reject(new Error('Printing feature is disabled'));
  224. }
  225. };
  226. WebContents.prototype.print = function (...args) {
  227. if (features.isPrintingEnabled()) {
  228. this._print(...args);
  229. } else {
  230. console.error('Error: Printing feature is disabled.');
  231. }
  232. };
  233. WebContents.prototype.getPrinters = function () {
  234. if (features.isPrintingEnabled()) {
  235. return this._getPrinters();
  236. } else {
  237. console.error('Error: Printing feature is disabled.');
  238. return [];
  239. }
  240. };
  241. WebContents.prototype.loadFile = function (filePath, options = {}) {
  242. if (typeof filePath !== 'string') {
  243. throw new Error('Must pass filePath as a string');
  244. }
  245. const { query, search, hash } = options;
  246. return this.loadURL(url.format({
  247. protocol: 'file',
  248. slashes: true,
  249. pathname: path.resolve(app.getAppPath(), filePath),
  250. query,
  251. search,
  252. hash
  253. }));
  254. };
  255. const addReplyToEvent = (event) => {
  256. event.reply = (...args) => {
  257. event.sender.sendToFrame(event.frameId, ...args);
  258. };
  259. };
  260. const addReplyInternalToEvent = (event) => {
  261. Object.defineProperty(event, '_replyInternal', {
  262. configurable: false,
  263. enumerable: false,
  264. value: (...args) => {
  265. event.sender._sendToFrameInternal(event.frameId, ...args);
  266. }
  267. });
  268. };
  269. const addReturnValueToEvent = (event) => {
  270. Object.defineProperty(event, 'returnValue', {
  271. set: (value) => event.sendReply([value]),
  272. get: () => {}
  273. });
  274. };
  275. // Add JavaScript wrappers for WebContents class.
  276. WebContents.prototype._init = function () {
  277. // The navigation controller.
  278. NavigationController.call(this, this);
  279. // Every remote callback from renderer process would add a listener to the
  280. // render-view-deleted event, so ignore the listeners warning.
  281. this.setMaxListeners(0);
  282. // Dispatch IPC messages to the ipc module.
  283. this.on('-ipc-message', function (event, internal, channel, args) {
  284. if (internal) {
  285. addReplyInternalToEvent(event);
  286. ipcMainInternal.emit(channel, event, ...args);
  287. } else {
  288. addReplyToEvent(event);
  289. this.emit('ipc-message', event, channel, ...args);
  290. ipcMain.emit(channel, event, ...args);
  291. }
  292. });
  293. this.on('-ipc-invoke', function (event, channel, args) {
  294. event._reply = (result) => event.sendReply({ result });
  295. event._throw = (error) => {
  296. console.error(`Error occurred in handler for '${channel}':`, error);
  297. event.sendReply({ error: error.toString() });
  298. };
  299. if (ipcMain._invokeHandlers.has(channel)) {
  300. ipcMain._invokeHandlers.get(channel)(event, ...args);
  301. } else {
  302. event._throw(`No handler registered for '${channel}'`);
  303. }
  304. });
  305. this.on('-ipc-message-sync', function (event, internal, channel, args) {
  306. addReturnValueToEvent(event);
  307. if (internal) {
  308. addReplyInternalToEvent(event);
  309. ipcMainInternal.emit(channel, event, ...args);
  310. } else {
  311. addReplyToEvent(event);
  312. this.emit('ipc-message-sync', event, channel, ...args);
  313. ipcMain.emit(channel, event, ...args);
  314. }
  315. });
  316. // Handle context menu action request from pepper plugin.
  317. this.on('pepper-context-menu', function (event, params, callback) {
  318. // Access Menu via electron.Menu to prevent circular require.
  319. const menu = electron.Menu.buildFromTemplate(params.menu);
  320. menu.popup({
  321. window: event.sender.getOwnerBrowserWindow(),
  322. x: params.x,
  323. y: params.y,
  324. callback
  325. });
  326. });
  327. this.on('crashed', (event, ...args) => {
  328. app.emit('renderer-process-crashed', event, this, ...args);
  329. });
  330. // The devtools requests the webContents to reload.
  331. this.on('devtools-reload-page', function () {
  332. this.reload();
  333. });
  334. // Handle window.open for BrowserWindow and BrowserView.
  335. if (['browserView', 'window'].includes(this.getType())) {
  336. // Make new windows requested by links behave like "window.open".
  337. this.on('-new-window', (event, url, frameName, disposition,
  338. additionalFeatures, postData,
  339. referrer) => {
  340. const options = {
  341. show: true,
  342. width: 800,
  343. height: 600
  344. };
  345. internalWindowOpen(event, url, referrer, frameName, disposition, options, additionalFeatures, postData);
  346. });
  347. // Create a new browser window for the native implementation of
  348. // "window.open", used in sandbox and nativeWindowOpen mode.
  349. this.on('-add-new-contents', (event, webContents, disposition,
  350. userGesture, left, top, width, height, url, frameName) => {
  351. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  352. disposition !== 'background-tab')) {
  353. event.preventDefault();
  354. return;
  355. }
  356. const options = {
  357. show: true,
  358. x: left,
  359. y: top,
  360. width: width || 800,
  361. height: height || 600,
  362. webContents
  363. };
  364. const referrer = { url: '', policy: 'default' };
  365. internalWindowOpen(event, url, referrer, frameName, disposition, options);
  366. });
  367. }
  368. this.on('login', (event, ...args) => {
  369. app.emit('login', event, this, ...args);
  370. });
  371. const event = process.electronBinding('event').createEmpty();
  372. app.emit('web-contents-created', event, this);
  373. };
  374. // Deprecations
  375. deprecate.fnToProperty(WebContents.prototype, 'audioMuted', '_isAudioMuted', '_setAudioMuted');
  376. deprecate.fnToProperty(WebContents.prototype, 'userAgent', '_getUserAgent', '_setUserAgent');
  377. deprecate.fnToProperty(WebContents.prototype, 'zoomLevel', '_getZoomLevel', '_setZoomLevel');
  378. deprecate.fnToProperty(WebContents.prototype, 'zoomFactor', '_getZoomFactor', '_setZoomFactor');
  379. deprecate.fnToProperty(WebContents.prototype, 'frameRate', '_getFrameRate', '_setFrameRate');
  380. // JavaScript wrapper of Debugger.
  381. const { Debugger } = process.electronBinding('debugger');
  382. Object.setPrototypeOf(Debugger.prototype, EventEmitter.prototype);
  383. // Public APIs.
  384. module.exports = {
  385. create (options = {}) {
  386. return binding.create(options);
  387. },
  388. fromId (id) {
  389. return binding.fromId(id);
  390. },
  391. getFocusedWebContents () {
  392. let focused = null;
  393. for (const contents of binding.getAllWebContents()) {
  394. if (!contents.isFocused()) continue;
  395. if (focused == null) focused = contents;
  396. // Return webview web contents which may be embedded inside another
  397. // web contents that is also reporting as focused
  398. if (contents.getType() === 'webview') return contents;
  399. }
  400. return focused;
  401. },
  402. getAllWebContents () {
  403. return binding.getAllWebContents();
  404. }
  405. };