web-contents.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 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 errorUtils = require('@electron/internal/common/error-utils')
  12. // session is not used here, the purpose is to make sure session is initalized
  13. // before the webContents module.
  14. // eslint-disable-next-line
  15. session
  16. let nextId = 0
  17. const getNextId = function () {
  18. return ++nextId
  19. }
  20. // Stock page sizes
  21. const PDFPageSizes = {
  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. }
  60. // Default printing setting
  61. const defaultPrintingSetting = {
  62. pageRage: [],
  63. mediaSize: {},
  64. landscape: false,
  65. color: 2,
  66. headerFooterEnabled: false,
  67. marginsType: 0,
  68. isFirstRequest: false,
  69. requestID: getNextId(),
  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. 'setLayoutZoomLevelLimits',
  154. 'setVisualZoomLevelLimits'
  155. ]
  156. for (const method of webFrameMethods) {
  157. WebContents.prototype[method] = function (...args) {
  158. ipcMainUtils.invokeInWebContents(this, false, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, ...args)
  159. }
  160. }
  161. const executeJavaScript = (contents, code, hasUserGesture) => {
  162. return ipcMainUtils.invokeInWebContents(contents, false, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', 'executeJavaScript', code, hasUserGesture)
  163. }
  164. // Make sure WebContents::executeJavaScript would run the code only when the
  165. // WebContents has been loaded.
  166. WebContents.prototype.executeJavaScript = function (code, hasUserGesture) {
  167. if (this.getURL() && !this.isLoadingMainFrame()) {
  168. return executeJavaScript(this, code, hasUserGesture)
  169. } else {
  170. return new Promise((resolve, reject) => {
  171. this.once('did-stop-loading', () => {
  172. executeJavaScript(this, code, hasUserGesture).then(resolve, reject)
  173. })
  174. })
  175. }
  176. }
  177. // TODO(codebytere): remove when promisifications is complete
  178. const nativeZoomLevel = WebContents.prototype.getZoomLevel
  179. WebContents.prototype.getZoomLevel = function (callback) {
  180. if (callback == null) {
  181. return nativeZoomLevel.call(this)
  182. } else {
  183. process.nextTick(() => {
  184. callback(nativeZoomLevel.call(this))
  185. })
  186. }
  187. }
  188. // TODO(codebytere): remove when promisifications is complete
  189. const nativeZoomFactor = WebContents.prototype.getZoomFactor
  190. WebContents.prototype.getZoomFactor = function (callback) {
  191. if (callback == null) {
  192. return nativeZoomFactor.call(this)
  193. } else {
  194. process.nextTick(() => {
  195. callback(nativeZoomFactor.call(this))
  196. })
  197. }
  198. }
  199. WebContents.prototype.takeHeapSnapshot = function (filePath) {
  200. return new Promise((resolve, reject) => {
  201. this._takeHeapSnapshot(filePath, (success) => {
  202. if (success) {
  203. resolve()
  204. } else {
  205. reject(new Error('takeHeapSnapshot failed'))
  206. }
  207. })
  208. })
  209. }
  210. // Translate the options of printToPDF.
  211. WebContents.prototype.printToPDF = function (options) {
  212. const printingSetting = Object.assign({}, defaultPrintingSetting)
  213. if (options.landscape) {
  214. printingSetting.landscape = options.landscape
  215. }
  216. if (options.marginsType) {
  217. printingSetting.marginsType = options.marginsType
  218. }
  219. if (options.printSelectionOnly) {
  220. printingSetting.shouldPrintSelectionOnly = options.printSelectionOnly
  221. }
  222. if (options.printBackground) {
  223. printingSetting.shouldPrintBackgrounds = options.printBackground
  224. }
  225. if (options.pageSize) {
  226. const pageSize = options.pageSize
  227. if (typeof pageSize === 'object') {
  228. if (!pageSize.height || !pageSize.width) {
  229. return Promise.reject(new Error('Must define height and width for pageSize'))
  230. }
  231. // Dimensions in Microns
  232. // 1 meter = 10^6 microns
  233. printingSetting.mediaSize = {
  234. name: 'CUSTOM',
  235. custom_display_name: 'Custom',
  236. height_microns: Math.ceil(pageSize.height),
  237. width_microns: Math.ceil(pageSize.width)
  238. }
  239. } else if (PDFPageSizes[pageSize]) {
  240. printingSetting.mediaSize = PDFPageSizes[pageSize]
  241. } else {
  242. return Promise.reject(new Error(`Does not support pageSize with ${pageSize}`))
  243. }
  244. } else {
  245. printingSetting.mediaSize = PDFPageSizes['A4']
  246. }
  247. // Chromium expects this in a 0-100 range number, not as float
  248. printingSetting.scaleFactor *= 100
  249. if (features.isPrintingEnabled()) {
  250. return this._printToPDF(printingSetting)
  251. } else {
  252. return Promise.reject(new Error('Printing feature is disabled'))
  253. }
  254. }
  255. WebContents.prototype.print = function (...args) {
  256. if (features.isPrintingEnabled()) {
  257. this._print(...args)
  258. } else {
  259. console.error('Error: Printing feature is disabled.')
  260. }
  261. }
  262. WebContents.prototype.getPrinters = function () {
  263. if (features.isPrintingEnabled()) {
  264. return this._getPrinters()
  265. } else {
  266. console.error('Error: Printing feature is disabled.')
  267. }
  268. }
  269. WebContents.prototype.loadFile = function (filePath, options = {}) {
  270. if (typeof filePath !== 'string') {
  271. throw new Error('Must pass filePath as a string')
  272. }
  273. const { query, search, hash } = options
  274. return this.loadURL(url.format({
  275. protocol: 'file',
  276. slashes: true,
  277. pathname: path.resolve(app.getAppPath(), filePath),
  278. query,
  279. search,
  280. hash
  281. }))
  282. }
  283. WebContents.prototype.capturePage = deprecate.promisify(WebContents.prototype.capturePage)
  284. WebContents.prototype.executeJavaScript = deprecate.promisify(WebContents.prototype.executeJavaScript)
  285. WebContents.prototype.printToPDF = deprecate.promisify(WebContents.prototype.printToPDF)
  286. WebContents.prototype.savePage = deprecate.promisify(WebContents.prototype.savePage)
  287. const addReplyToEvent = (event) => {
  288. event.reply = (...args) => {
  289. event.sender.sendToFrame(event.frameId, ...args)
  290. }
  291. }
  292. const addReplyInternalToEvent = (event) => {
  293. Object.defineProperty(event, '_replyInternal', {
  294. configurable: false,
  295. enumerable: false,
  296. value: (...args) => {
  297. event.sender._sendToFrameInternal(event.frameId, ...args)
  298. }
  299. })
  300. }
  301. const addReturnValueToEvent = (event) => {
  302. Object.defineProperty(event, 'returnValue', {
  303. set: (value) => event.sendReply([value]),
  304. get: () => {}
  305. })
  306. }
  307. // Add JavaScript wrappers for WebContents class.
  308. WebContents.prototype._init = function () {
  309. // The navigation controller.
  310. NavigationController.call(this, this)
  311. // Every remote callback from renderer process would add a listener to the
  312. // render-view-deleted event, so ignore the listeners warning.
  313. this.setMaxListeners(0)
  314. // Dispatch IPC messages to the ipc module.
  315. this.on('-ipc-message', function (event, internal, channel, args) {
  316. if (internal) {
  317. addReplyInternalToEvent(event)
  318. ipcMainInternal.emit(channel, event, ...args)
  319. } else {
  320. addReplyToEvent(event)
  321. this.emit('ipc-message', event, channel, ...args)
  322. ipcMain.emit(channel, event, ...args)
  323. }
  324. })
  325. this.on('-ipc-message-sync', function (event, internal, channel, args) {
  326. addReturnValueToEvent(event)
  327. if (internal) {
  328. addReplyInternalToEvent(event)
  329. ipcMainInternal.emit(channel, event, ...args)
  330. } else {
  331. addReplyToEvent(event)
  332. this.emit('ipc-message-sync', event, channel, ...args)
  333. ipcMain.emit(channel, event, ...args)
  334. }
  335. })
  336. // Handle context menu action request from pepper plugin.
  337. this.on('pepper-context-menu', function (event, params, callback) {
  338. // Access Menu via electron.Menu to prevent circular require.
  339. const menu = electron.Menu.buildFromTemplate(params.menu)
  340. menu.popup({
  341. window: event.sender.getOwnerBrowserWindow(),
  342. x: params.x,
  343. y: params.y,
  344. callback
  345. })
  346. })
  347. const forwardedEvents = [
  348. 'desktop-capturer-get-sources',
  349. 'remote-require',
  350. 'remote-get-global',
  351. 'remote-get-builtin',
  352. 'remote-get-current-window',
  353. 'remote-get-current-web-contents',
  354. 'remote-get-guest-web-contents'
  355. ]
  356. for (const eventName of forwardedEvents) {
  357. this.on(eventName, (event, ...args) => {
  358. app.emit(eventName, event, this, ...args)
  359. })
  360. }
  361. this.on('crashed', (event, ...args) => {
  362. app.emit('renderer-process-crashed', event, this, ...args)
  363. })
  364. deprecate.event(this, 'did-get-response-details', '-did-get-response-details')
  365. deprecate.event(this, 'did-get-redirect-request', '-did-get-redirect-request')
  366. // The devtools requests the webContents to reload.
  367. this.on('devtools-reload-page', function () {
  368. this.reload()
  369. })
  370. // Handle window.open for BrowserWindow and BrowserView.
  371. if (['browserView', 'window'].includes(this.getType())) {
  372. // Make new windows requested by links behave like "window.open".
  373. this.on('-new-window', (event, url, frameName, disposition,
  374. additionalFeatures, postData,
  375. referrer) => {
  376. const options = {
  377. show: true,
  378. width: 800,
  379. height: 600
  380. }
  381. ipcMainInternal.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN',
  382. event, url, referrer, frameName, disposition,
  383. options, additionalFeatures, postData)
  384. })
  385. // Create a new browser window for the native implementation of
  386. // "window.open", used in sandbox and nativeWindowOpen mode.
  387. this.on('-add-new-contents', (event, webContents, disposition,
  388. userGesture, left, top, width, height, url, frameName) => {
  389. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  390. disposition !== 'background-tab')) {
  391. event.preventDefault()
  392. return
  393. }
  394. const options = {
  395. show: true,
  396. x: left,
  397. y: top,
  398. width: width || 800,
  399. height: height || 600,
  400. webContents
  401. }
  402. const referrer = { url: '', policy: 'default' }
  403. ipcMainInternal.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN',
  404. event, url, referrer, frameName, disposition, options)
  405. })
  406. }
  407. app.emit('web-contents-created', {}, this)
  408. }
  409. // JavaScript wrapper of Debugger.
  410. const { Debugger } = process.electronBinding('debugger')
  411. Debugger.prototype.sendCommand = deprecate.promisify(Debugger.prototype.sendCommand)
  412. Object.setPrototypeOf(Debugger.prototype, EventEmitter.prototype)
  413. // Public APIs.
  414. module.exports = {
  415. create (options = {}) {
  416. return binding.create(options)
  417. },
  418. fromId (id) {
  419. return binding.fromId(id)
  420. },
  421. getFocusedWebContents () {
  422. let focused = null
  423. for (const contents of binding.getAllWebContents()) {
  424. if (!contents.isFocused()) continue
  425. if (focused == null) focused = contents
  426. // Return webview web contents which may be embedded inside another
  427. // web contents that is also reporting as focused
  428. if (contents.getType() === 'webview') return contents
  429. }
  430. return focused
  431. },
  432. getAllWebContents () {
  433. return binding.getAllWebContents()
  434. }
  435. }