web-contents.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 v8Util = process.atomBinding('v8_util')
  8. const { app, ipcMain, session, NavigationController, deprecate } = electron
  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. requestID: getNextId(),
  69. previewUIID: 0,
  70. previewModifiable: true,
  71. printToPDF: true,
  72. printWithCloudPrint: false,
  73. printWithPrivet: false,
  74. printWithExtension: false,
  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. // Following methods are mapped to webFrame.
  128. const webFrameMethods = [
  129. 'insertCSS',
  130. 'insertText',
  131. 'setLayoutZoomLevelLimits',
  132. 'setVisualZoomLevelLimits'
  133. ]
  134. const asyncWebFrameMethods = function (requestId, method, callback, ...args) {
  135. return new Promise((resolve, reject) => {
  136. ipcMainInternal.once(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, function (event, error, result) {
  137. if (error == null) {
  138. if (typeof callback === 'function') callback(result)
  139. resolve(result)
  140. } else {
  141. reject(errorUtils.deserialize(error))
  142. }
  143. })
  144. this._sendInternal('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args)
  145. })
  146. }
  147. for (const method of webFrameMethods) {
  148. WebContents.prototype[method] = function (...args) {
  149. this._sendInternal('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, args)
  150. }
  151. }
  152. // Make sure WebContents::executeJavaScript would run the code only when the
  153. // WebContents has been loaded.
  154. WebContents.prototype.executeJavaScript = function (code, hasUserGesture, callback) {
  155. const requestId = getNextId()
  156. if (typeof hasUserGesture === 'function') {
  157. // Shift.
  158. callback = hasUserGesture
  159. hasUserGesture = null
  160. }
  161. if (hasUserGesture == null) {
  162. hasUserGesture = false
  163. }
  164. if (this.getURL() && !this.isLoadingMainFrame()) {
  165. return asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture)
  166. } else {
  167. return new Promise((resolve, reject) => {
  168. this.once('did-stop-loading', () => {
  169. asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture).then(resolve).catch(reject)
  170. })
  171. })
  172. }
  173. }
  174. WebContents.prototype.takeHeapSnapshot = function (filePath) {
  175. return new Promise((resolve, reject) => {
  176. const channel = `ELECTRON_TAKE_HEAP_SNAPSHOT_RESULT_${getNextId()}`
  177. ipcMainInternal.once(channel, (event, success) => {
  178. if (success) {
  179. resolve()
  180. } else {
  181. reject(new Error('takeHeapSnapshot failed'))
  182. }
  183. })
  184. if (!this._takeHeapSnapshot(filePath, channel)) {
  185. ipcMainInternal.emit(channel, false)
  186. }
  187. })
  188. }
  189. // Translate the options of printToPDF.
  190. WebContents.prototype.printToPDF = function (options, callback) {
  191. const printingSetting = Object.assign({}, defaultPrintingSetting)
  192. if (options.landscape) {
  193. printingSetting.landscape = options.landscape
  194. }
  195. if (options.marginsType) {
  196. printingSetting.marginsType = options.marginsType
  197. }
  198. if (options.printSelectionOnly) {
  199. printingSetting.shouldPrintSelectionOnly = options.printSelectionOnly
  200. }
  201. if (options.printBackground) {
  202. printingSetting.shouldPrintBackgrounds = options.printBackground
  203. }
  204. if (options.pageSize) {
  205. const pageSize = options.pageSize
  206. if (typeof pageSize === 'object') {
  207. if (!pageSize.height || !pageSize.width) {
  208. return callback(new Error('Must define height and width for pageSize'))
  209. }
  210. // Dimensions in Microns
  211. // 1 meter = 10^6 microns
  212. printingSetting.mediaSize = {
  213. name: 'CUSTOM',
  214. custom_display_name: 'Custom',
  215. height_microns: Math.ceil(pageSize.height),
  216. width_microns: Math.ceil(pageSize.width)
  217. }
  218. } else if (PDFPageSizes[pageSize]) {
  219. printingSetting.mediaSize = PDFPageSizes[pageSize]
  220. } else {
  221. return callback(new Error(`Does not support pageSize with ${pageSize}`))
  222. }
  223. } else {
  224. printingSetting.mediaSize = PDFPageSizes['A4']
  225. }
  226. // Chromium expects this in a 0-100 range number, not as float
  227. printingSetting.scaleFactor *= 100
  228. if (features.isPrintingEnabled()) {
  229. this._printToPDF(printingSetting, callback)
  230. } else {
  231. console.error('Error: Printing feature is disabled.')
  232. }
  233. }
  234. WebContents.prototype.print = function (...args) {
  235. if (features.isPrintingEnabled()) {
  236. this._print(...args)
  237. } else {
  238. console.error('Error: Printing feature is disabled.')
  239. }
  240. }
  241. WebContents.prototype.getPrinters = function () {
  242. if (features.isPrintingEnabled()) {
  243. return this._getPrinters()
  244. } else {
  245. console.error('Error: Printing feature is disabled.')
  246. }
  247. }
  248. WebContents.prototype.getZoomLevel = function (callback) {
  249. if (typeof callback !== 'function') {
  250. throw new Error('Must pass function as an argument')
  251. }
  252. process.nextTick(() => {
  253. const zoomLevel = this._getZoomLevel()
  254. callback(zoomLevel)
  255. })
  256. }
  257. WebContents.prototype.loadFile = function (filePath, options = {}) {
  258. if (typeof filePath !== 'string') {
  259. throw new Error('Must pass filePath as a string')
  260. }
  261. const { query, search, hash } = options
  262. return this.loadURL(url.format({
  263. protocol: 'file',
  264. slashes: true,
  265. pathname: path.resolve(app.getAppPath(), filePath),
  266. query,
  267. search,
  268. hash
  269. }))
  270. }
  271. WebContents.prototype.getZoomFactor = function (callback) {
  272. if (typeof callback !== 'function') {
  273. throw new Error('Must pass function as an argument')
  274. }
  275. process.nextTick(() => {
  276. const zoomFactor = this._getZoomFactor()
  277. callback(zoomFactor)
  278. })
  279. }
  280. WebContents.prototype.findInPage = function (text, options = {}) {
  281. // TODO (nitsakh): Remove in 5.0
  282. if (options.wordStart != null || options.medialCapitalAtWordStart != null) {
  283. deprecate.log('wordStart and medialCapitalAtWordStart options are deprecated')
  284. }
  285. return this._findInPage(text, options)
  286. }
  287. const safeProtocols = new Set([
  288. 'chrome-devtools:',
  289. 'chrome-extension:'
  290. ])
  291. const isWebContentsTrusted = function (contents) {
  292. const pageURL = contents._getURL()
  293. const { protocol } = url.parse(pageURL)
  294. return safeProtocols.has(protocol)
  295. }
  296. // Add JavaScript wrappers for WebContents class.
  297. WebContents.prototype._init = function () {
  298. // The navigation controller.
  299. NavigationController.call(this, this)
  300. // Every remote callback from renderer process would add a listenter to the
  301. // render-view-deleted event, so ignore the listenters warning.
  302. this.setMaxListeners(0)
  303. // Dispatch IPC messages to the ipc module.
  304. this.on('ipc-message', function (event, [channel, ...args]) {
  305. ipcMain.emit(channel, event, ...args)
  306. })
  307. this.on('ipc-message-sync', function (event, [channel, ...args]) {
  308. Object.defineProperty(event, 'returnValue', {
  309. set: function (value) {
  310. return event.sendReply([value])
  311. },
  312. get: function () {}
  313. })
  314. ipcMain.emit(channel, event, ...args)
  315. })
  316. this.on('ipc-internal-message', function (event, [channel, ...args]) {
  317. ipcMainInternal.emit(channel, event, ...args)
  318. })
  319. this.on('ipc-internal-message-sync', function (event, [channel, ...args]) {
  320. Object.defineProperty(event, 'returnValue', {
  321. set: function (value) {
  322. return event.sendReply([value])
  323. },
  324. get: function () {}
  325. })
  326. ipcMainInternal.emit(channel, event, ...args)
  327. })
  328. // Handle context menu action request from pepper plugin.
  329. this.on('pepper-context-menu', function (event, params, callback) {
  330. // Access Menu via electron.Menu to prevent circular require.
  331. const menu = electron.Menu.buildFromTemplate(params.menu)
  332. menu.popup({
  333. window: event.sender.getOwnerBrowserWindow(),
  334. x: params.x,
  335. y: params.y,
  336. callback
  337. })
  338. })
  339. const forwardedEvents = [
  340. 'remote-require',
  341. 'remote-get-global',
  342. 'remote-get-builtin',
  343. 'remote-get-current-window',
  344. 'remote-get-current-web-contents',
  345. 'remote-get-guest-web-contents'
  346. ]
  347. for (const eventName of forwardedEvents) {
  348. this.on(eventName, (event, ...args) => {
  349. if (!isWebContentsTrusted(event.sender)) {
  350. app.emit(eventName, event, this, ...args)
  351. }
  352. })
  353. }
  354. deprecate.event(this, 'did-get-response-details', '-did-get-response-details')
  355. deprecate.event(this, 'did-get-redirect-request', '-did-get-redirect-request')
  356. // The devtools requests the webContents to reload.
  357. this.on('devtools-reload-page', function () {
  358. this.reload()
  359. })
  360. // Handle window.open for BrowserWindow and BrowserView.
  361. if (['browserView', 'window'].includes(this.getType())) {
  362. // Make new windows requested by links behave like "window.open"
  363. this.webContents.on('-new-window', (event, url, frameName, disposition,
  364. additionalFeatures, postData,
  365. referrer) => {
  366. const options = {
  367. show: true,
  368. width: 800,
  369. height: 600
  370. }
  371. ipcMainInternal.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN',
  372. event, url, referrer, frameName, disposition,
  373. options, additionalFeatures, postData)
  374. })
  375. this.webContents.on('-web-contents-created', (event, webContents, url,
  376. frameName) => {
  377. v8Util.setHiddenValue(webContents, 'url-framename', { url, frameName })
  378. })
  379. // Create a new browser window for the native implementation of
  380. // "window.open", used in sandbox and nativeWindowOpen mode
  381. this.webContents.on('-add-new-contents', (event, webContents, disposition,
  382. userGesture, left, top, width,
  383. height) => {
  384. const urlFrameName = v8Util.getHiddenValue(webContents, 'url-framename')
  385. if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
  386. disposition !== 'background-tab') || !urlFrameName) {
  387. event.preventDefault()
  388. return
  389. }
  390. if (webContents.getLastWebPreferences().nodeIntegration === true) {
  391. const message =
  392. 'Enabling Node.js integration in child windows opened with the ' +
  393. '"nativeWindowOpen" option will cause memory leaks, please turn off ' +
  394. 'the "nodeIntegration" option.\\n' +
  395. 'From 5.x child windows opened with the "nativeWindowOpen" option ' +
  396. 'will always have Node.js integration disabled.\\n' +
  397. 'See https://github.com/electron/electron/pull/15076 for more.'
  398. // console is only available after DOM is created.
  399. const printWarning = () => this.webContents.executeJavaScript(`console.warn('${message}')`)
  400. if (this.webContents.isDomReady()) {
  401. printWarning()
  402. } else {
  403. this.webContents.once('dom-ready', printWarning)
  404. }
  405. }
  406. const { url, frameName } = urlFrameName
  407. v8Util.deleteHiddenValue(webContents, 'url-framename')
  408. const options = {
  409. show: true,
  410. x: left,
  411. y: top,
  412. width: width || 800,
  413. height: height || 600,
  414. webContents
  415. }
  416. const referrer = { url: '', policy: 'default' }
  417. ipcMainInternal.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN',
  418. event, url, referrer, frameName, disposition, options)
  419. })
  420. }
  421. app.emit('web-contents-created', {}, this)
  422. }
  423. // JavaScript wrapper of Debugger.
  424. const { Debugger } = process.atomBinding('debugger')
  425. Object.setPrototypeOf(Debugger.prototype, EventEmitter.prototype)
  426. // Public APIs.
  427. module.exports = {
  428. create (options = {}) {
  429. return binding.create(options)
  430. },
  431. fromId (id) {
  432. return binding.fromId(id)
  433. },
  434. getFocusedWebContents () {
  435. let focused = null
  436. for (const contents of binding.getAllWebContents()) {
  437. if (!contents.isFocused()) continue
  438. if (focused == null) focused = contents
  439. // Return webview web contents which may be embedded inside another
  440. // web contents that is also reporting as focused
  441. if (contents.getType() === 'webview') return contents
  442. }
  443. return focused
  444. },
  445. getAllWebContents () {
  446. return binding.getAllWebContents()
  447. }
  448. }