web-contents.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. 'use strict'
  2. const features = process.atomBinding('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 errorUtils = require('@electron/internal/common/error-utils')
  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. // Stock page sizes
  20. const PDFPageSizes = {
  21. A5: {
  22. custom_display_name: 'A5',
  23. height_microns: 210000,
  24. name: 'ISO_A5',
  25. width_microns: 148000
  26. },
  27. A4: {
  28. custom_display_name: 'A4',
  29. height_microns: 297000,
  30. name: 'ISO_A4',
  31. is_default: 'true',
  32. width_microns: 210000
  33. },
  34. A3: {
  35. custom_display_name: 'A3',
  36. height_microns: 420000,
  37. name: 'ISO_A3',
  38. width_microns: 297000
  39. },
  40. Legal: {
  41. custom_display_name: 'Legal',
  42. height_microns: 355600,
  43. name: 'NA_LEGAL',
  44. width_microns: 215900
  45. },
  46. Letter: {
  47. custom_display_name: 'Letter',
  48. height_microns: 279400,
  49. name: 'NA_LETTER',
  50. width_microns: 215900
  51. },
  52. Tabloid: {
  53. height_microns: 431800,
  54. name: 'NA_LEDGER',
  55. width_microns: 279400,
  56. custom_display_name: 'Tabloid'
  57. }
  58. }
  59. // Default printing setting
  60. const defaultPrintingSetting = {
  61. pageRage: [],
  62. mediaSize: {},
  63. landscape: false,
  64. color: 2,
  65. headerFooterEnabled: false,
  66. marginsType: 0,
  67. isFirstRequest: false,
  68. previewUIID: 0,
  69. previewModifiable: true,
  70. printToPDF: true,
  71. printWithCloudPrint: false,
  72. printWithPrivet: false,
  73. printWithExtension: false,
  74. pagesPerSheet: 1,
  75. deviceName: 'Save as PDF',
  76. generateDraftData: true,
  77. fitToPageEnabled: false,
  78. scaleFactor: 1,
  79. dpiHorizontal: 72,
  80. dpiVertical: 72,
  81. rasterizePDF: false,
  82. duplex: 0,
  83. copies: 1,
  84. collate: true,
  85. shouldPrintBackgrounds: false,
  86. shouldPrintSelectionOnly: false
  87. }
  88. // JavaScript implementations of WebContents.
  89. const binding = process.atomBinding('web_contents')
  90. const { WebContents } = binding
  91. Object.setPrototypeOf(NavigationController.prototype, EventEmitter.prototype)
  92. Object.setPrototypeOf(WebContents.prototype, NavigationController.prototype)
  93. // WebContents::send(channel, args..)
  94. // WebContents::sendToAll(channel, args..)
  95. WebContents.prototype.send = function (channel, ...args) {
  96. if (typeof channel !== 'string') {
  97. throw new Error('Missing required channel argument')
  98. }
  99. const internal = false
  100. const sendToAll = false
  101. return this._send(internal, sendToAll, channel, args)
  102. }
  103. WebContents.prototype.sendToAll = function (channel, ...args) {
  104. if (typeof channel !== 'string') {
  105. throw new Error('Missing required channel argument')
  106. }
  107. const internal = false
  108. const sendToAll = true
  109. return this._send(internal, sendToAll, channel, args)
  110. }
  111. WebContents.prototype._sendInternal = function (channel, ...args) {
  112. if (typeof channel !== 'string') {
  113. throw new Error('Missing required channel argument')
  114. }
  115. const internal = true
  116. const sendToAll = false
  117. return this._send(internal, sendToAll, channel, args)
  118. }
  119. WebContents.prototype._sendInternalToAll = function (channel, ...args) {
  120. if (typeof channel !== 'string') {
  121. throw new Error('Missing required channel argument')
  122. }
  123. const internal = true
  124. const sendToAll = true
  125. return this._send(internal, sendToAll, channel, args)
  126. }
  127. WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
  128. if (typeof channel !== 'string') {
  129. throw new Error('Missing required channel argument')
  130. } else if (typeof frameId !== 'number') {
  131. throw new Error('Missing required frameId argument')
  132. }
  133. const internal = false
  134. const sendToAll = false
  135. return this._sendToFrame(internal, sendToAll, frameId, channel, args)
  136. }
  137. WebContents.prototype._sendToFrameInternal = function (frameId, channel, ...args) {
  138. if (typeof channel !== 'string') {
  139. throw new Error('Missing required channel argument')
  140. } else if (typeof frameId !== 'number') {
  141. throw new Error('Missing required frameId argument')
  142. }
  143. const internal = true
  144. const sendToAll = false
  145. return this._sendToFrame(internal, sendToAll, frameId, channel, args)
  146. }
  147. // Following methods are mapped to webFrame.
  148. const webFrameMethods = [
  149. 'insertCSS',
  150. 'insertText',
  151. 'setLayoutZoomLevelLimits',
  152. 'setVisualZoomLevelLimits'
  153. ]
  154. const asyncWebFrameMethods = function (requestId, method, callback, ...args) {
  155. return new Promise((resolve, reject) => {
  156. ipcMainInternal.once(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, function (event, error, result) {
  157. if (error == null) {
  158. if (typeof callback === 'function') callback(result)
  159. resolve(result)
  160. } else {
  161. reject(errorUtils.deserialize(error))
  162. }
  163. })
  164. this._sendInternal('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args)
  165. })
  166. }
  167. for (const method of webFrameMethods) {
  168. WebContents.prototype[method] = function (...args) {
  169. this._sendInternal('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, args)
  170. }
  171. }
  172. // Make sure WebContents::executeJavaScript would run the code only when the
  173. // WebContents has been loaded.
  174. WebContents.prototype.executeJavaScript = function (code, hasUserGesture, callback) {
  175. const requestId = getNextId()
  176. if (typeof hasUserGesture === 'function') {
  177. // Shift.
  178. callback = hasUserGesture
  179. hasUserGesture = null
  180. }
  181. if (hasUserGesture == null) {
  182. hasUserGesture = false
  183. }
  184. if (this.getURL() && !this.isLoadingMainFrame()) {
  185. return asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture)
  186. } else {
  187. return new Promise((resolve, reject) => {
  188. this.once('did-stop-loading', () => {
  189. asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture).then(resolve).catch(reject)
  190. })
  191. })
  192. }
  193. }
  194. // TODO(codebytere): remove when promisifications is complete
  195. const nativeZoomLevel = WebContents.prototype.getZoomLevel
  196. WebContents.prototype.getZoomLevel = function (callback) {
  197. if (callback == null) {
  198. return nativeZoomLevel.call(this)
  199. } else {
  200. process.nextTick(() => {
  201. callback(nativeZoomLevel.call(this))
  202. })
  203. }
  204. }
  205. // TODO(codebytere): remove when promisifications is complete
  206. const nativeZoomFactor = WebContents.prototype.getZoomFactor
  207. WebContents.prototype.getZoomFactor = function (callback) {
  208. if (callback == null) {
  209. return nativeZoomFactor.call(this)
  210. } else {
  211. process.nextTick(() => {
  212. callback(nativeZoomFactor.call(this))
  213. })
  214. }
  215. }
  216. WebContents.prototype.takeHeapSnapshot = function (filePath) {
  217. return new Promise((resolve, reject) => {
  218. const channel = `ELECTRON_TAKE_HEAP_SNAPSHOT_RESULT_${getNextId()}`
  219. ipcMainInternal.once(channel, (event, success) => {
  220. if (success) {
  221. resolve()
  222. } else {
  223. reject(new Error('takeHeapSnapshot failed'))
  224. }
  225. })
  226. if (!this._takeHeapSnapshot(filePath, channel)) {
  227. ipcMainInternal.emit(channel, false)
  228. }
  229. })
  230. }
  231. // Translate the options of printToPDF.
  232. WebContents.prototype.printToPDF = function (options, callback) {
  233. const printingSetting = {
  234. ...defaultPrintingSetting,
  235. requestID: getNextId()
  236. }
  237. if (options.landscape) {
  238. printingSetting.landscape = options.landscape
  239. }
  240. if (options.marginsType) {
  241. printingSetting.marginsType = options.marginsType
  242. }
  243. if (options.printSelectionOnly) {
  244. printingSetting.shouldPrintSelectionOnly = options.printSelectionOnly
  245. }
  246. if (options.printBackground) {
  247. printingSetting.shouldPrintBackgrounds = options.printBackground
  248. }
  249. if (options.pageSize) {
  250. const pageSize = options.pageSize
  251. if (typeof pageSize === 'object') {
  252. if (!pageSize.height || !pageSize.width) {
  253. return callback(new Error('Must define height and width for pageSize'))
  254. }
  255. // Dimensions in Microns
  256. // 1 meter = 10^6 microns
  257. printingSetting.mediaSize = {
  258. name: 'CUSTOM',
  259. custom_display_name: 'Custom',
  260. height_microns: Math.ceil(pageSize.height),
  261. width_microns: Math.ceil(pageSize.width)
  262. }
  263. } else if (PDFPageSizes[pageSize]) {
  264. printingSetting.mediaSize = PDFPageSizes[pageSize]
  265. } else {
  266. return callback(new Error(`Does not support pageSize with ${pageSize}`))
  267. }
  268. } else {
  269. printingSetting.mediaSize = PDFPageSizes['A4']
  270. }
  271. // Chromium expects this in a 0-100 range number, not as float
  272. printingSetting.scaleFactor *= 100
  273. if (features.isPrintingEnabled()) {
  274. this._printToPDF(printingSetting, callback)
  275. } else {
  276. console.error('Error: Printing feature is disabled.')
  277. }
  278. }
  279. WebContents.prototype.print = function (...args) {
  280. if (features.isPrintingEnabled()) {
  281. this._print(...args)
  282. } else {
  283. console.error('Error: Printing feature is disabled.')
  284. }
  285. }
  286. WebContents.prototype.getPrinters = function () {
  287. if (features.isPrintingEnabled()) {
  288. return this._getPrinters()
  289. } else {
  290. console.error('Error: Printing feature is disabled.')
  291. }
  292. }
  293. WebContents.prototype.loadFile = function (filePath, options = {}) {
  294. if (typeof filePath !== 'string') {
  295. throw new Error('Must pass filePath as a string')
  296. }
  297. const { query, search, hash } = options
  298. return this.loadURL(url.format({
  299. protocol: 'file',
  300. slashes: true,
  301. pathname: path.resolve(app.getAppPath(), filePath),
  302. query,
  303. search,
  304. hash
  305. }))
  306. }
  307. const addReplyToEvent = (event) => {
  308. event.reply = (...args) => {
  309. event.sender.sendToFrame(event.frameId, ...args)
  310. }
  311. }
  312. const addReplyInternalToEvent = (event) => {
  313. Object.defineProperty(event, '_replyInternal', {
  314. configurable: false,
  315. enumerable: false,
  316. value: (...args) => {
  317. event.sender._sendToFrameInternal(event.frameId, ...args)
  318. }
  319. })
  320. }
  321. const safeProtocols = new Set([
  322. 'chrome-devtools:',
  323. 'chrome-extension:'
  324. ])
  325. const isWebContentsTrusted = function (contents) {
  326. const pageURL = contents._getURL()
  327. const { protocol } = url.parse(pageURL)
  328. return safeProtocols.has(protocol)
  329. }
  330. // Add JavaScript wrappers for WebContents class.
  331. WebContents.prototype._init = function () {
  332. // The navigation controller.
  333. NavigationController.call(this, this)
  334. // Every remote callback from renderer process would add a listener to the
  335. // render-view-deleted event, so ignore the listeners warning.
  336. this.setMaxListeners(0)
  337. this.capturePage = deprecate.promisify(this.capturePage)
  338. this.hasServiceWorker = deprecate.function(this.hasServiceWorker)
  339. this.unregisterServiceWorker = deprecate.function(this.unregisterServiceWorker)
  340. // Dispatch IPC messages to the ipc module.
  341. this.on('-ipc-message', function (event, [channel, ...args]) {
  342. addReplyToEvent(event)
  343. this.emit('ipc-message', event, channel, ...args)
  344. ipcMain.emit(channel, event, ...args)
  345. })
  346. this.on('-ipc-message-sync', function (event, [channel, ...args]) {
  347. Object.defineProperty(event, 'returnValue', {
  348. set: function (value) {
  349. return event.sendReply([value])
  350. },
  351. get: function () {}
  352. })
  353. addReplyToEvent(event)
  354. this.emit('ipc-message-sync', event, channel, ...args)
  355. ipcMain.emit(channel, event, ...args)
  356. })
  357. this.on('ipc-internal-message', function (event, [channel, ...args]) {
  358. addReplyInternalToEvent(event)
  359. ipcMainInternal.emit(channel, event, ...args)
  360. })
  361. this.on('ipc-internal-message-sync', function (event, [channel, ...args]) {
  362. Object.defineProperty(event, 'returnValue', {
  363. set: function (value) {
  364. return event.sendReply([value])
  365. },
  366. get: function () {}
  367. })
  368. addReplyInternalToEvent(event)
  369. ipcMainInternal.emit(channel, event, ...args)
  370. })
  371. // Handle context menu action request from pepper plugin.
  372. this.on('pepper-context-menu', function (event, params, callback) {
  373. // Access Menu via electron.Menu to prevent circular require.
  374. const menu = electron.Menu.buildFromTemplate(params.menu)
  375. menu.popup({
  376. window: event.sender.getOwnerBrowserWindow(),
  377. x: params.x,
  378. y: params.y,
  379. callback
  380. })
  381. })
  382. const forwardedEvents = [
  383. 'desktop-capturer-get-sources',
  384. 'remote-require',
  385. 'remote-get-global',
  386. 'remote-get-builtin',
  387. 'remote-get-current-window',
  388. 'remote-get-current-web-contents',
  389. 'remote-get-guest-web-contents'
  390. ]
  391. for (const eventName of forwardedEvents) {
  392. this.on(eventName, (event, ...args) => {
  393. if (!isWebContentsTrusted(event.sender)) {
  394. app.emit(eventName, event, this, ...args)
  395. }
  396. })
  397. }
  398. deprecate.event(this, 'did-get-response-details', '-did-get-response-details')
  399. deprecate.event(this, 'did-get-redirect-request', '-did-get-redirect-request')
  400. // The devtools requests the webContents to reload.
  401. this.on('devtools-reload-page', function () {
  402. this.reload()
  403. })
  404. // Handle window.open for BrowserWindow and BrowserView.
  405. if (['browserView', 'window'].includes(this.getType())) {
  406. // Make new windows requested by links behave like "window.open".
  407. this.on('-new-window', (event, url, frameName, disposition,
  408. additionalFeatures, postData,
  409. referrer) => {
  410. const options = {
  411. show: true,
  412. width: 800,
  413. height: 600
  414. }
  415. ipcMainInternal.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN',
  416. event, url, referrer, frameName, disposition,
  417. options, additionalFeatures, postData)
  418. })
  419. // Create a new browser window for the native implementation of
  420. // "window.open", used in sandbox and nativeWindowOpen mode.
  421. this.on('-add-new-contents', (event, webContents, disposition,
  422. userGesture, left, top, width, height, url, frameName) => {
  423. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  424. disposition !== 'background-tab')) {
  425. event.preventDefault()
  426. return
  427. }
  428. const options = {
  429. show: true,
  430. x: left,
  431. y: top,
  432. width: width || 800,
  433. height: height || 600,
  434. webContents
  435. }
  436. const referrer = { url: '', policy: 'default' }
  437. ipcMainInternal.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN',
  438. event, url, referrer, frameName, disposition, options)
  439. })
  440. }
  441. app.emit('web-contents-created', {}, this)
  442. }
  443. // JavaScript wrapper of Debugger.
  444. const { Debugger } = process.atomBinding('debugger')
  445. Debugger.prototype.sendCommand = deprecate.promisify(Debugger.prototype.sendCommand)
  446. Object.setPrototypeOf(Debugger.prototype, EventEmitter.prototype)
  447. // Public APIs.
  448. module.exports = {
  449. create (options = {}) {
  450. return binding.create(options)
  451. },
  452. fromId (id) {
  453. return binding.fromId(id)
  454. },
  455. getFocusedWebContents () {
  456. let focused = null
  457. for (const contents of binding.getAllWebContents()) {
  458. if (!contents.isFocused()) continue
  459. if (focused == null) focused = contents
  460. // Return webview web contents which may be embedded inside another
  461. // web contents that is also reporting as focused
  462. if (contents.getType() === 'webview') return contents
  463. }
  464. return focused
  465. },
  466. getAllWebContents () {
  467. return binding.getAllWebContents()
  468. }
  469. }