main.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. // Deprecated APIs are still supported and should be tested.
  2. process.throwDeprecation = false
  3. const electron = require('electron')
  4. const { app, BrowserWindow, crashReporter, dialog, ipcMain, protocol, webContents } = electron
  5. const { Coverage } = require('electabul')
  6. const fs = require('fs')
  7. const path = require('path')
  8. const util = require('util')
  9. const v8 = require('v8')
  10. const argv = require('yargs')
  11. .boolean('ci')
  12. .string('g').alias('g', 'grep')
  13. .boolean('i').alias('i', 'invert')
  14. .argv
  15. let window = null
  16. // will be used by crash-reporter spec.
  17. process.port = 0
  18. process.crashServicePid = 0
  19. v8.setFlagsFromString('--expose_gc')
  20. app.commandLine.appendSwitch('js-flags', '--expose_gc')
  21. app.commandLine.appendSwitch('ignore-certificate-errors')
  22. app.commandLine.appendSwitch('disable-renderer-backgrounding')
  23. // Disable security warnings (the security warnings test will enable them)
  24. process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = true
  25. // Accessing stdout in the main process will result in the process.stdout
  26. // throwing UnknownSystemError in renderer process sometimes. This line makes
  27. // sure we can reproduce it in renderer process.
  28. // eslint-disable-next-line
  29. process.stdout
  30. // Adding a variable for sandbox process.env test validation
  31. process.env.sandboxmain = ''
  32. // Access console to reproduce #3482.
  33. // eslint-disable-next-line
  34. console
  35. ipcMain.on('message', function (event, ...args) {
  36. event.sender.send('message', ...args)
  37. })
  38. // Set productName so getUploadedReports() uses the right directory in specs
  39. if (process.platform !== 'darwin') {
  40. crashReporter.productName = 'Zombies'
  41. }
  42. // Write output to file if OUTPUT_TO_FILE is defined.
  43. const outputToFile = process.env.OUTPUT_TO_FILE
  44. const print = function (_, args) {
  45. const output = util.format.apply(null, args)
  46. if (outputToFile) {
  47. fs.appendFileSync(outputToFile, output + '\n')
  48. } else {
  49. console.error(output)
  50. }
  51. }
  52. ipcMain.on('console.log', print)
  53. ipcMain.on('console.error', print)
  54. ipcMain.on('process.exit', function (event, code) {
  55. process.exit(code)
  56. })
  57. ipcMain.on('eval', function (event, script) {
  58. event.returnValue = eval(script) // eslint-disable-line
  59. })
  60. ipcMain.on('echo', function (event, msg) {
  61. event.returnValue = msg
  62. })
  63. global.setTimeoutPromisified = util.promisify(setTimeout)
  64. global.permissionChecks = {
  65. allow: () => electron.session.defaultSession.setPermissionCheckHandler(null),
  66. reject: () => electron.session.defaultSession.setPermissionCheckHandler(() => false)
  67. }
  68. const coverage = new Coverage({
  69. outputPath: path.join(__dirname, '..', '..', 'out', 'coverage')
  70. })
  71. coverage.setup()
  72. ipcMain.on('get-main-process-coverage', function (event) {
  73. event.returnValue = global.__coverage__ || null
  74. })
  75. global.isCi = !!argv.ci
  76. if (global.isCi) {
  77. process.removeAllListeners('uncaughtException')
  78. process.on('uncaughtException', function (error) {
  79. console.error(error, error.stack)
  80. process.exit(1)
  81. })
  82. }
  83. global.nativeModulesEnabled = !process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS
  84. // Register app as standard scheme.
  85. global.standardScheme = 'app'
  86. global.zoomScheme = 'zoom'
  87. protocol.registerStandardSchemes([global.standardScheme, global.zoomScheme], { secure: true })
  88. app.on('window-all-closed', function () {
  89. app.quit()
  90. })
  91. app.on('web-contents-created', (event, contents) => {
  92. contents.on('crashed', (event, killed) => {
  93. console.log(`webContents ${contents.id} crashed: ${contents.getURL()} (killed=${killed})`)
  94. })
  95. })
  96. app.on('ready', function () {
  97. // Test if using protocol module would crash.
  98. electron.protocol.registerStringProtocol('test-if-crashes', function () {})
  99. // Send auto updater errors to window to be verified in specs
  100. electron.autoUpdater.on('error', function (error) {
  101. window.send('auto-updater-error', error.message)
  102. })
  103. window = new BrowserWindow({
  104. title: 'Electron Tests',
  105. show: !global.isCi,
  106. width: 800,
  107. height: 600,
  108. webPreferences: {
  109. backgroundThrottling: false
  110. }
  111. })
  112. window.loadFile('static/index.html', {
  113. query: {
  114. grep: argv.grep,
  115. invert: argv.invert ? 'true' : ''
  116. }
  117. })
  118. window.on('unresponsive', function () {
  119. const chosen = dialog.showMessageBox(window, {
  120. type: 'warning',
  121. buttons: ['Close', 'Keep Waiting'],
  122. message: 'Window is not responsing',
  123. detail: 'The window is not responding. Would you like to force close it or just keep waiting?'
  124. })
  125. if (chosen === 0) window.destroy()
  126. })
  127. window.webContents.on('crashed', function () {
  128. console.error('Renderer process crashed')
  129. process.exit(1)
  130. })
  131. // For session's download test, listen 'will-download' event in browser, and
  132. // reply the result to renderer for verifying
  133. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf')
  134. ipcMain.on('set-download-option', function (event, needCancel, preventDefault, filePath = downloadFilePath) {
  135. window.webContents.session.once('will-download', function (e, item) {
  136. window.webContents.send('download-created',
  137. item.getState(),
  138. item.getURLChain(),
  139. item.getMimeType(),
  140. item.getReceivedBytes(),
  141. item.getTotalBytes(),
  142. item.getFilename(),
  143. item.getSavePath())
  144. if (preventDefault) {
  145. e.preventDefault()
  146. const url = item.getURL()
  147. const filename = item.getFilename()
  148. setImmediate(function () {
  149. try {
  150. item.getURL()
  151. } catch (err) {
  152. window.webContents.send('download-error', url, filename, err.message)
  153. }
  154. })
  155. } else {
  156. if (item.getState() === 'interrupted' && !needCancel) {
  157. item.resume()
  158. } else {
  159. item.setSavePath(filePath)
  160. }
  161. item.on('done', function (e, state) {
  162. window.webContents.send('download-done',
  163. state,
  164. item.getURL(),
  165. item.getMimeType(),
  166. item.getReceivedBytes(),
  167. item.getTotalBytes(),
  168. item.getContentDisposition(),
  169. item.getFilename(),
  170. item.getSavePath(),
  171. item.getURLChain(),
  172. item.getLastModifiedTime(),
  173. item.getETag())
  174. })
  175. if (needCancel) item.cancel()
  176. }
  177. })
  178. event.returnValue = 'done'
  179. })
  180. ipcMain.on('prevent-next-input-event', (event, key, id) => {
  181. webContents.fromId(id).once('before-input-event', (event, input) => {
  182. if (key === input.key) event.preventDefault()
  183. })
  184. event.returnValue = null
  185. })
  186. ipcMain.on('executeJavaScript', function (event, code, hasCallback) {
  187. let promise
  188. if (hasCallback) {
  189. promise = window.webContents.executeJavaScript(code, (result) => {
  190. window.webContents.send('executeJavaScript-response', result)
  191. })
  192. } else {
  193. promise = window.webContents.executeJavaScript(code)
  194. }
  195. promise.then((result) => {
  196. window.webContents.send('executeJavaScript-promise-response', result)
  197. }).catch((error) => {
  198. window.webContents.send('executeJavaScript-promise-error', error)
  199. if (error && error.name) {
  200. window.webContents.send('executeJavaScript-promise-error-name', error.name)
  201. }
  202. })
  203. if (!hasCallback) {
  204. event.returnValue = 'success'
  205. }
  206. })
  207. })
  208. for (const eventName of [
  209. 'remote-require',
  210. 'remote-get-global',
  211. 'remote-get-builtin'
  212. ]) {
  213. ipcMain.on(`handle-next-${eventName}`, function (event, valuesMap = {}) {
  214. event.sender.once(eventName, (event, name) => {
  215. if (valuesMap.hasOwnProperty(name)) {
  216. event.returnValue = valuesMap[name]
  217. } else {
  218. event.preventDefault()
  219. }
  220. })
  221. })
  222. }
  223. for (const eventName of [
  224. 'remote-get-current-window',
  225. 'remote-get-current-web-contents',
  226. 'remote-get-guest-web-contents'
  227. ]) {
  228. ipcMain.on(`handle-next-${eventName}`, function (event, returnValue) {
  229. event.sender.once(eventName, (event) => {
  230. if (returnValue) {
  231. event.returnValue = returnValue
  232. } else {
  233. event.preventDefault()
  234. }
  235. })
  236. })
  237. }
  238. ipcMain.on('set-client-certificate-option', function (event, skip) {
  239. app.once('select-client-certificate', function (event, webContents, url, list, callback) {
  240. event.preventDefault()
  241. if (skip) {
  242. callback()
  243. } else {
  244. ipcMain.on('client-certificate-response', function (event, certificate) {
  245. callback(certificate)
  246. })
  247. window.webContents.send('select-client-certificate', webContents.id, list)
  248. }
  249. })
  250. event.returnValue = 'done'
  251. })
  252. ipcMain.on('close-on-will-navigate', (event, id) => {
  253. const contents = event.sender
  254. const window = BrowserWindow.fromId(id)
  255. window.webContents.once('will-navigate', (event, input) => {
  256. window.close()
  257. contents.send('closed-on-will-navigate')
  258. })
  259. })
  260. ipcMain.on('close-on-will-redirect', (event, id) => {
  261. const contents = event.sender
  262. const window = BrowserWindow.fromId(id)
  263. window.webContents.once('will-redirect', (event, input) => {
  264. window.close()
  265. contents.send('closed-on-will-redirect')
  266. })
  267. })
  268. ipcMain.on('prevent-will-redirect', (event, id) => {
  269. const window = BrowserWindow.fromId(id)
  270. window.webContents.once('will-redirect', (event) => {
  271. event.preventDefault()
  272. })
  273. })
  274. ipcMain.on('create-window-with-options-cycle', (event) => {
  275. // This can't be done over remote since cycles are already
  276. // nulled out at the IPC layer
  277. const foo = {}
  278. foo.bar = foo
  279. foo.baz = {
  280. hello: {
  281. world: true
  282. }
  283. }
  284. foo.baz2 = foo.baz
  285. const window = new BrowserWindow({ show: false, foo: foo })
  286. event.returnValue = window.id
  287. })
  288. ipcMain.on('prevent-next-new-window', (event, id) => {
  289. webContents.fromId(id).once('new-window', event => event.preventDefault())
  290. })
  291. ipcMain.on('set-web-preferences-on-next-new-window', (event, id, key, value) => {
  292. webContents.fromId(id).once('new-window', (event, url, frameName, disposition, options) => {
  293. options.webPreferences[key] = value
  294. })
  295. })
  296. ipcMain.on('prevent-next-will-attach-webview', (event) => {
  297. event.sender.once('will-attach-webview', event => event.preventDefault())
  298. })
  299. ipcMain.on('prevent-next-will-prevent-unload', (event, id) => {
  300. webContents.fromId(id).once('will-prevent-unload', event => event.preventDefault())
  301. })
  302. ipcMain.on('disable-node-on-next-will-attach-webview', (event, id) => {
  303. event.sender.once('will-attach-webview', (event, webPreferences, params) => {
  304. params.src = `file://${path.join(__dirname, '..', 'fixtures', 'pages', 'c.html')}`
  305. webPreferences.nodeIntegration = false
  306. })
  307. })
  308. ipcMain.on('disable-preload-on-next-will-attach-webview', (event, id) => {
  309. event.sender.once('will-attach-webview', (event, webPreferences, params) => {
  310. params.src = `file://${path.join(__dirname, '..', 'fixtures', 'pages', 'webview-stripped-preload.html')}`
  311. delete webPreferences.preload
  312. delete webPreferences.preloadURL
  313. })
  314. })
  315. ipcMain.on('try-emit-web-contents-event', (event, id, eventName) => {
  316. const consoleWarn = console.warn
  317. const contents = webContents.fromId(id)
  318. const listenerCountBefore = contents.listenerCount(eventName)
  319. console.warn = (warningMessage) => {
  320. console.warn = consoleWarn
  321. const listenerCountAfter = contents.listenerCount(eventName)
  322. event.returnValue = {
  323. warningMessage,
  324. listenerCountBefore,
  325. listenerCountAfter
  326. }
  327. }
  328. contents.emit(eventName, { sender: contents })
  329. })
  330. ipcMain.on('handle-uncaught-exception', (event, message) => {
  331. suspendListeners(process, 'uncaughtException', (error) => {
  332. event.returnValue = error.message
  333. })
  334. fs.readFile(__filename, () => {
  335. throw new Error(message)
  336. })
  337. })
  338. ipcMain.on('handle-unhandled-rejection', (event, message) => {
  339. suspendListeners(process, 'unhandledRejection', (error) => {
  340. event.returnValue = error.message
  341. })
  342. fs.readFile(__filename, () => {
  343. Promise.reject(new Error(message))
  344. })
  345. })
  346. ipcMain.on('crash-service-pid', (event, pid) => {
  347. process.crashServicePid = pid
  348. event.returnValue = null
  349. })
  350. ipcMain.on('test-webcontents-navigation-observer', (event, options) => {
  351. let contents = null
  352. let destroy = () => {}
  353. if (options.id) {
  354. const w = BrowserWindow.fromId(options.id)
  355. contents = w.webContents
  356. destroy = () => w.close()
  357. } else {
  358. contents = webContents.create()
  359. destroy = () => contents.destroy()
  360. }
  361. contents.once(options.name, () => destroy())
  362. contents.once('destroyed', () => {
  363. event.sender.send(options.responseEvent)
  364. })
  365. contents.loadURL(options.url)
  366. })
  367. ipcMain.on('test-browserwindow-destroy', (event, testOptions) => {
  368. const focusListener = (event, win) => win.id
  369. app.on('browser-window-focus', focusListener)
  370. const windowCount = 3
  371. const windowOptions = {
  372. show: false,
  373. width: 400,
  374. height: 400,
  375. webPreferences: {
  376. backgroundThrottling: false
  377. }
  378. }
  379. const windows = Array.from(Array(windowCount)).map(x => new BrowserWindow(windowOptions))
  380. windows.forEach(win => win.show())
  381. windows.forEach(win => win.focus())
  382. windows.forEach(win => win.destroy())
  383. app.removeListener('browser-window-focus', focusListener)
  384. event.sender.send(testOptions.responseEvent)
  385. })
  386. // Suspend listeners until the next event and then restore them
  387. const suspendListeners = (emitter, eventName, callback) => {
  388. const listeners = emitter.listeners(eventName)
  389. emitter.removeAllListeners(eventName)
  390. emitter.once(eventName, (...args) => {
  391. emitter.removeAllListeners(eventName)
  392. listeners.forEach((listener) => {
  393. emitter.on(eventName, listener)
  394. })
  395. // eslint-disable-next-line standard/no-callback-literal
  396. callback(...args)
  397. })
  398. }