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 { 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. '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 = {
  213. ...defaultPrintingSetting,
  214. requestID: getNextId()
  215. }
  216. if (options.landscape) {
  217. printingSetting.landscape = options.landscape
  218. }
  219. if (options.marginsType) {
  220. printingSetting.marginsType = options.marginsType
  221. }
  222. if (options.printSelectionOnly) {
  223. printingSetting.shouldPrintSelectionOnly = options.printSelectionOnly
  224. }
  225. if (options.printBackground) {
  226. printingSetting.shouldPrintBackgrounds = options.printBackground
  227. }
  228. if (options.pageSize) {
  229. const pageSize = options.pageSize
  230. if (typeof pageSize === 'object') {
  231. if (!pageSize.height || !pageSize.width) {
  232. return Promise.reject(new Error('Must define height and width for pageSize'))
  233. }
  234. // Dimensions in Microns
  235. // 1 meter = 10^6 microns
  236. printingSetting.mediaSize = {
  237. name: 'CUSTOM',
  238. custom_display_name: 'Custom',
  239. height_microns: Math.ceil(pageSize.height),
  240. width_microns: Math.ceil(pageSize.width)
  241. }
  242. } else if (PDFPageSizes[pageSize]) {
  243. printingSetting.mediaSize = PDFPageSizes[pageSize]
  244. } else {
  245. return Promise.reject(new Error(`Does not support pageSize with ${pageSize}`))
  246. }
  247. } else {
  248. printingSetting.mediaSize = PDFPageSizes['A4']
  249. }
  250. // Chromium expects this in a 0-100 range number, not as float
  251. printingSetting.scaleFactor *= 100
  252. if (features.isPrintingEnabled()) {
  253. return this._printToPDF(printingSetting)
  254. } else {
  255. return Promise.reject(new Error('Printing feature is disabled'))
  256. }
  257. }
  258. WebContents.prototype.print = function (...args) {
  259. if (features.isPrintingEnabled()) {
  260. this._print(...args)
  261. } else {
  262. console.error('Error: Printing feature is disabled.')
  263. }
  264. }
  265. WebContents.prototype.getPrinters = function () {
  266. if (features.isPrintingEnabled()) {
  267. return this._getPrinters()
  268. } else {
  269. console.error('Error: Printing feature is disabled.')
  270. }
  271. }
  272. WebContents.prototype.loadFile = function (filePath, options = {}) {
  273. if (typeof filePath !== 'string') {
  274. throw new Error('Must pass filePath as a string')
  275. }
  276. const { query, search, hash } = options
  277. return this.loadURL(url.format({
  278. protocol: 'file',
  279. slashes: true,
  280. pathname: path.resolve(app.getAppPath(), filePath),
  281. query,
  282. search,
  283. hash
  284. }))
  285. }
  286. WebContents.prototype.capturePage = deprecate.promisify(WebContents.prototype.capturePage)
  287. WebContents.prototype.executeJavaScript = deprecate.promisify(WebContents.prototype.executeJavaScript)
  288. WebContents.prototype.printToPDF = deprecate.promisify(WebContents.prototype.printToPDF)
  289. WebContents.prototype.savePage = deprecate.promisify(WebContents.prototype.savePage)
  290. const addReplyToEvent = (event) => {
  291. event.reply = (...args) => {
  292. event.sender.sendToFrame(event.frameId, ...args)
  293. }
  294. }
  295. const addReplyInternalToEvent = (event) => {
  296. Object.defineProperty(event, '_replyInternal', {
  297. configurable: false,
  298. enumerable: false,
  299. value: (...args) => {
  300. event.sender._sendToFrameInternal(event.frameId, ...args)
  301. }
  302. })
  303. }
  304. const addReturnValueToEvent = (event) => {
  305. Object.defineProperty(event, 'returnValue', {
  306. set: (value) => event.sendReply([value]),
  307. get: () => {}
  308. })
  309. }
  310. // Add JavaScript wrappers for WebContents class.
  311. WebContents.prototype._init = function () {
  312. // The navigation controller.
  313. NavigationController.call(this, this)
  314. // Every remote callback from renderer process would add a listener to the
  315. // render-view-deleted event, so ignore the listeners warning.
  316. this.setMaxListeners(0)
  317. // Dispatch IPC messages to the ipc module.
  318. this.on('-ipc-message', function (event, internal, channel, args) {
  319. if (internal) {
  320. addReplyInternalToEvent(event)
  321. ipcMainInternal.emit(channel, event, ...args)
  322. } else {
  323. addReplyToEvent(event)
  324. this.emit('ipc-message', event, channel, ...args)
  325. ipcMain.emit(channel, event, ...args)
  326. }
  327. })
  328. this.on('-ipc-message-sync', function (event, internal, channel, args) {
  329. addReturnValueToEvent(event)
  330. if (internal) {
  331. addReplyInternalToEvent(event)
  332. ipcMainInternal.emit(channel, event, ...args)
  333. } else {
  334. addReplyToEvent(event)
  335. this.emit('ipc-message-sync', event, channel, ...args)
  336. ipcMain.emit(channel, event, ...args)
  337. }
  338. })
  339. // Handle context menu action request from pepper plugin.
  340. this.on('pepper-context-menu', function (event, params, callback) {
  341. // Access Menu via electron.Menu to prevent circular require.
  342. const menu = electron.Menu.buildFromTemplate(params.menu)
  343. menu.popup({
  344. window: event.sender.getOwnerBrowserWindow(),
  345. x: params.x,
  346. y: params.y,
  347. callback
  348. })
  349. })
  350. const forwardedEvents = [
  351. 'desktop-capturer-get-sources',
  352. 'remote-require',
  353. 'remote-get-global',
  354. 'remote-get-builtin',
  355. 'remote-get-current-window',
  356. 'remote-get-current-web-contents',
  357. 'remote-get-guest-web-contents'
  358. ]
  359. for (const eventName of forwardedEvents) {
  360. this.on(eventName, (event, ...args) => {
  361. app.emit(eventName, event, this, ...args)
  362. })
  363. }
  364. this.on('crashed', (event, ...args) => {
  365. app.emit('renderer-process-crashed', event, this, ...args)
  366. })
  367. deprecate.event(this, 'did-get-response-details', '-did-get-response-details')
  368. deprecate.event(this, 'did-get-redirect-request', '-did-get-redirect-request')
  369. // The devtools requests the webContents to reload.
  370. this.on('devtools-reload-page', function () {
  371. this.reload()
  372. })
  373. // Handle window.open for BrowserWindow and BrowserView.
  374. if (['browserView', 'window'].includes(this.getType())) {
  375. // Make new windows requested by links behave like "window.open".
  376. this.on('-new-window', (event, url, frameName, disposition,
  377. additionalFeatures, postData,
  378. referrer) => {
  379. const options = {
  380. show: true,
  381. width: 800,
  382. height: 600
  383. }
  384. internalWindowOpen(event, url, referrer, frameName, disposition, options, additionalFeatures, postData)
  385. })
  386. // Create a new browser window for the native implementation of
  387. // "window.open", used in sandbox and nativeWindowOpen mode.
  388. this.on('-add-new-contents', (event, webContents, disposition,
  389. userGesture, left, top, width, height, url, frameName) => {
  390. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  391. disposition !== 'background-tab')) {
  392. event.preventDefault()
  393. return
  394. }
  395. const options = {
  396. show: true,
  397. x: left,
  398. y: top,
  399. width: width || 800,
  400. height: height || 600,
  401. webContents
  402. }
  403. const referrer = { url: '', policy: 'default' }
  404. internalWindowOpen(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. }