chromium-spec.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. const { expect } = require('chai');
  2. const fs = require('fs');
  3. const http = require('http');
  4. const path = require('path');
  5. const ws = require('ws');
  6. const url = require('url');
  7. const ChildProcess = require('child_process');
  8. const { ipcRenderer } = require('electron');
  9. const { emittedOnce } = require('./events-helpers');
  10. const { resolveGetters } = require('./expect-helpers');
  11. const features = process.electronBinding('features');
  12. /* Most of the APIs here don't use standard callbacks */
  13. /* eslint-disable standard/no-callback-literal */
  14. describe('chromium feature', () => {
  15. const fixtures = path.resolve(__dirname, 'fixtures');
  16. let listener = null;
  17. afterEach(() => {
  18. if (listener != null) {
  19. window.removeEventListener('message', listener);
  20. }
  21. listener = null;
  22. });
  23. describe('Badging API', () => {
  24. it('does not crash', () => {
  25. expect(() => {
  26. navigator.setAppBadge(42);
  27. }).to.not.throw();
  28. });
  29. });
  30. describe('heap snapshot', () => {
  31. it('does not crash', function () {
  32. process.electronBinding('v8_util').takeHeapSnapshot();
  33. });
  34. });
  35. describe('navigator.webkitGetUserMedia', () => {
  36. it('calls its callbacks', (done) => {
  37. navigator.webkitGetUserMedia({
  38. audio: true,
  39. video: false
  40. }, () => done(),
  41. () => done());
  42. });
  43. });
  44. describe('navigator.language', () => {
  45. it('should not be empty', () => {
  46. expect(navigator.language).to.not.equal('');
  47. });
  48. });
  49. describe('navigator.geolocation', () => {
  50. before(function () {
  51. if (!features.isFakeLocationProviderEnabled()) {
  52. return this.skip();
  53. }
  54. });
  55. it('returns position when permission is granted', (done) => {
  56. navigator.geolocation.getCurrentPosition((position) => {
  57. expect(position).to.have.a.property('coords');
  58. expect(position).to.have.a.property('timestamp');
  59. done();
  60. }, (error) => {
  61. done(error);
  62. });
  63. });
  64. });
  65. describe('window.open', () => {
  66. it('accepts "nodeIntegration" as feature', (done) => {
  67. let b = null;
  68. listener = (event) => {
  69. expect(event.data.isProcessGlobalUndefined).to.be.true();
  70. b.close();
  71. done();
  72. };
  73. window.addEventListener('message', listener);
  74. b = window.open(`file://${fixtures}/pages/window-opener-node.html`, '', 'nodeIntegration=no,show=no');
  75. });
  76. it('inherit options of parent window', (done) => {
  77. let b = null;
  78. listener = (event) => {
  79. const width = outerWidth;
  80. const height = outerHeight;
  81. expect(event.data).to.equal(`size: ${width} ${height}`);
  82. b.close();
  83. done();
  84. };
  85. window.addEventListener('message', listener);
  86. b = window.open(`file://${fixtures}/pages/window-open-size.html`, '', 'show=no');
  87. });
  88. it('disables node integration when it is disabled on the parent window', (done) => {
  89. let b = null;
  90. listener = (event) => {
  91. expect(event.data.isProcessGlobalUndefined).to.be.true();
  92. b.close();
  93. done();
  94. };
  95. window.addEventListener('message', listener);
  96. const windowUrl = require('url').format({
  97. pathname: `${fixtures}/pages/window-opener-no-node-integration.html`,
  98. protocol: 'file',
  99. query: {
  100. p: `${fixtures}/pages/window-opener-node.html`
  101. },
  102. slashes: true
  103. });
  104. b = window.open(windowUrl, '', 'nodeIntegration=no,show=no');
  105. });
  106. it('disables the <webview> tag when it is disabled on the parent window', (done) => {
  107. let b = null;
  108. listener = (event) => {
  109. expect(event.data.isWebViewGlobalUndefined).to.be.true();
  110. b.close();
  111. done();
  112. };
  113. window.addEventListener('message', listener);
  114. const windowUrl = require('url').format({
  115. pathname: `${fixtures}/pages/window-opener-no-webview-tag.html`,
  116. protocol: 'file',
  117. query: {
  118. p: `${fixtures}/pages/window-opener-webview.html`
  119. },
  120. slashes: true
  121. });
  122. b = window.open(windowUrl, '', 'webviewTag=no,nodeIntegration=yes,show=no');
  123. });
  124. it('does not override child options', (done) => {
  125. let b = null;
  126. const size = {
  127. width: 350,
  128. height: 450
  129. };
  130. listener = (event) => {
  131. expect(event.data).to.equal(`size: ${size.width} ${size.height}`);
  132. b.close();
  133. done();
  134. };
  135. window.addEventListener('message', listener);
  136. b = window.open(`file://${fixtures}/pages/window-open-size.html`, '', 'show=no,width=' + size.width + ',height=' + size.height);
  137. });
  138. it('throws an exception when the arguments cannot be converted to strings', () => {
  139. expect(() => {
  140. window.open('', { toString: null });
  141. }).to.throw('Cannot convert object to primitive value');
  142. expect(() => {
  143. window.open('', '', { toString: 3 });
  144. }).to.throw('Cannot convert object to primitive value');
  145. });
  146. it('does not throw an exception when the features include webPreferences', () => {
  147. let b = null;
  148. expect(() => {
  149. b = window.open('', '', 'webPreferences=');
  150. }).to.not.throw();
  151. b.close();
  152. });
  153. });
  154. describe('window.opener', () => {
  155. it('is not null for window opened by window.open', (done) => {
  156. let b = null;
  157. listener = (event) => {
  158. expect(event.data).to.equal('object');
  159. b.close();
  160. done();
  161. };
  162. window.addEventListener('message', listener);
  163. b = window.open(`file://${fixtures}/pages/window-opener.html`, '', 'show=no');
  164. });
  165. });
  166. describe('window.postMessage', () => {
  167. it('throws an exception when the targetOrigin cannot be converted to a string', () => {
  168. const b = window.open('');
  169. expect(() => {
  170. b.postMessage('test', { toString: null });
  171. }).to.throw('Cannot convert object to primitive value');
  172. b.close();
  173. });
  174. });
  175. describe('window.opener.postMessage', () => {
  176. it('sets source and origin correctly', (done) => {
  177. let b = null;
  178. listener = (event) => {
  179. window.removeEventListener('message', listener);
  180. expect(event.source).to.deep.equal(b);
  181. b.close();
  182. expect(event.origin).to.equal('file://');
  183. done();
  184. };
  185. window.addEventListener('message', listener);
  186. b = window.open(`file://${fixtures}/pages/window-opener-postMessage.html`, '', 'show=no');
  187. });
  188. it('supports windows opened from a <webview>', (done) => {
  189. const webview = new WebView();
  190. webview.addEventListener('console-message', (e) => {
  191. webview.remove();
  192. expect(e.message).to.equal('message');
  193. done();
  194. });
  195. webview.allowpopups = true;
  196. webview.src = url.format({
  197. pathname: `${fixtures}/pages/webview-opener-postMessage.html`,
  198. protocol: 'file',
  199. query: {
  200. p: `${fixtures}/pages/window-opener-postMessage.html`
  201. },
  202. slashes: true
  203. });
  204. document.body.appendChild(webview);
  205. });
  206. describe('targetOrigin argument', () => {
  207. let serverURL;
  208. let server;
  209. beforeEach((done) => {
  210. server = http.createServer((req, res) => {
  211. res.writeHead(200);
  212. const filePath = path.join(fixtures, 'pages', 'window-opener-targetOrigin.html');
  213. res.end(fs.readFileSync(filePath, 'utf8'));
  214. });
  215. server.listen(0, '127.0.0.1', () => {
  216. serverURL = `http://127.0.0.1:${server.address().port}`;
  217. done();
  218. });
  219. });
  220. afterEach(() => {
  221. server.close();
  222. });
  223. it('delivers messages that match the origin', (done) => {
  224. let b = null;
  225. listener = (event) => {
  226. window.removeEventListener('message', listener);
  227. b.close();
  228. expect(event.data).to.equal('deliver');
  229. done();
  230. };
  231. window.addEventListener('message', listener);
  232. b = window.open(serverURL, '', 'show=no');
  233. });
  234. });
  235. });
  236. describe('webgl', () => {
  237. before(function () {
  238. if (process.platform === 'win32') {
  239. this.skip();
  240. }
  241. });
  242. it('can be get as context in canvas', () => {
  243. if (process.platform === 'linux') {
  244. // FIXME(alexeykuzmin): Skip the test.
  245. // this.skip()
  246. return;
  247. }
  248. const webgl = document.createElement('canvas').getContext('webgl');
  249. expect(webgl).to.not.be.null();
  250. });
  251. });
  252. describe('web workers', () => {
  253. it('Worker can work', (done) => {
  254. const worker = new Worker('../fixtures/workers/worker.js');
  255. const message = 'ping';
  256. worker.onmessage = (event) => {
  257. expect(event.data).to.equal(message);
  258. worker.terminate();
  259. done();
  260. };
  261. worker.postMessage(message);
  262. });
  263. it('Worker has no node integration by default', (done) => {
  264. const worker = new Worker('../fixtures/workers/worker_node.js');
  265. worker.onmessage = (event) => {
  266. expect(event.data).to.equal('undefined undefined undefined undefined');
  267. worker.terminate();
  268. done();
  269. };
  270. });
  271. it('Worker has node integration with nodeIntegrationInWorker', (done) => {
  272. const webview = new WebView();
  273. webview.addEventListener('ipc-message', (e) => {
  274. expect(e.channel).to.equal('object function object function');
  275. webview.remove();
  276. done();
  277. });
  278. webview.src = `file://${fixtures}/pages/worker.html`;
  279. webview.setAttribute('webpreferences', 'nodeIntegration, nodeIntegrationInWorker');
  280. document.body.appendChild(webview);
  281. });
  282. // FIXME: disabled during chromium update due to crash in content::WorkerScriptFetchInitiator::CreateScriptLoaderOnIO
  283. xdescribe('SharedWorker', () => {
  284. it('can work', (done) => {
  285. const worker = new SharedWorker('../fixtures/workers/shared_worker.js');
  286. const message = 'ping';
  287. worker.port.onmessage = (event) => {
  288. expect(event.data).to.equal(message);
  289. done();
  290. };
  291. worker.port.postMessage(message);
  292. });
  293. it('has no node integration by default', (done) => {
  294. const worker = new SharedWorker('../fixtures/workers/shared_worker_node.js');
  295. worker.port.onmessage = (event) => {
  296. expect(event.data).to.equal('undefined undefined undefined undefined');
  297. done();
  298. };
  299. });
  300. it('has node integration with nodeIntegrationInWorker', (done) => {
  301. const webview = new WebView();
  302. webview.addEventListener('console-message', (e) => {
  303. console.log(e);
  304. });
  305. webview.addEventListener('ipc-message', (e) => {
  306. expect(e.channel).to.equal('object function object function');
  307. webview.remove();
  308. done();
  309. });
  310. webview.src = `file://${fixtures}/pages/shared_worker.html`;
  311. webview.setAttribute('webpreferences', 'nodeIntegration, nodeIntegrationInWorker');
  312. document.body.appendChild(webview);
  313. });
  314. });
  315. });
  316. describe('iframe', () => {
  317. let iframe = null;
  318. beforeEach(() => {
  319. iframe = document.createElement('iframe');
  320. });
  321. afterEach(() => {
  322. document.body.removeChild(iframe);
  323. });
  324. it('does not have node integration', (done) => {
  325. iframe.src = `file://${fixtures}/pages/set-global.html`;
  326. document.body.appendChild(iframe);
  327. iframe.onload = () => {
  328. expect(iframe.contentWindow.test).to.equal('undefined undefined undefined');
  329. done();
  330. };
  331. });
  332. });
  333. describe('storage', () => {
  334. describe('DOM storage quota increase', () => {
  335. ['localStorage', 'sessionStorage'].forEach((storageName) => {
  336. const storage = window[storageName];
  337. it(`allows saving at least 40MiB in ${storageName}`, (done) => {
  338. // Although JavaScript strings use UTF-16, the underlying
  339. // storage provider may encode strings differently, muddling the
  340. // translation between character and byte counts. However,
  341. // a string of 40 * 2^20 characters will require at least 40MiB
  342. // and presumably no more than 80MiB, a size guaranteed to
  343. // to exceed the original 10MiB quota yet stay within the
  344. // new 100MiB quota.
  345. // Note that both the key name and value affect the total size.
  346. const testKeyName = '_electronDOMStorageQuotaIncreasedTest';
  347. const length = 40 * Math.pow(2, 20) - testKeyName.length;
  348. storage.setItem(testKeyName, 'X'.repeat(length));
  349. // Wait at least one turn of the event loop to help avoid false positives
  350. // Although not entirely necessary, the previous version of this test case
  351. // failed to detect a real problem (perhaps related to DOM storage data caching)
  352. // wherein calling `getItem` immediately after `setItem` would appear to work
  353. // but then later (e.g. next tick) it would not.
  354. setTimeout(() => {
  355. expect(storage.getItem(testKeyName)).to.have.lengthOf(length);
  356. storage.removeItem(testKeyName);
  357. done();
  358. }, 1);
  359. });
  360. it(`throws when attempting to use more than 128MiB in ${storageName}`, () => {
  361. expect(() => {
  362. const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest';
  363. const length = 128 * Math.pow(2, 20) - testKeyName.length;
  364. try {
  365. storage.setItem(testKeyName, 'X'.repeat(length));
  366. } finally {
  367. storage.removeItem(testKeyName);
  368. }
  369. }).to.throw();
  370. });
  371. });
  372. });
  373. it('requesting persitent quota works', (done) => {
  374. navigator.webkitPersistentStorage.requestQuota(1024 * 1024, (grantedBytes) => {
  375. expect(grantedBytes).to.equal(1048576);
  376. done();
  377. });
  378. });
  379. });
  380. describe('websockets', () => {
  381. let wss = null;
  382. let server = null;
  383. const WebSocketServer = ws.Server;
  384. afterEach(() => {
  385. wss.close();
  386. server.close();
  387. });
  388. it('has user agent', (done) => {
  389. server = http.createServer();
  390. server.listen(0, '127.0.0.1', () => {
  391. const port = server.address().port;
  392. wss = new WebSocketServer({ server: server });
  393. wss.on('error', done);
  394. wss.on('connection', (ws, upgradeReq) => {
  395. if (upgradeReq.headers['user-agent']) {
  396. done();
  397. } else {
  398. done('user agent is empty');
  399. }
  400. });
  401. const socket = new WebSocket(`ws://127.0.0.1:${port}`);
  402. });
  403. });
  404. });
  405. describe('Promise', () => {
  406. it('resolves correctly in Node.js calls', (done) => {
  407. class XElement extends HTMLElement {}
  408. customElements.define('x-element', XElement);
  409. setImmediate(() => {
  410. let called = false;
  411. Promise.resolve().then(() => {
  412. done(called ? void 0 : new Error('wrong sequence'));
  413. });
  414. document.createElement('x-element');
  415. called = true;
  416. });
  417. });
  418. it('resolves correctly in Electron calls', (done) => {
  419. class YElement extends HTMLElement {}
  420. customElements.define('y-element', YElement);
  421. ipcRenderer.invoke('ping').then(() => {
  422. let called = false;
  423. Promise.resolve().then(() => {
  424. done(called ? void 0 : new Error('wrong sequence'));
  425. });
  426. document.createElement('y-element');
  427. called = true;
  428. });
  429. });
  430. });
  431. describe('fetch', () => {
  432. it('does not crash', (done) => {
  433. const server = http.createServer((req, res) => {
  434. res.end('test');
  435. server.close();
  436. });
  437. server.listen(0, '127.0.0.1', () => {
  438. const port = server.address().port;
  439. fetch(`http://127.0.0.1:${port}`).then((res) => res.body.getReader())
  440. .then((reader) => {
  441. reader.read().then((r) => {
  442. reader.cancel();
  443. done();
  444. });
  445. }).catch((e) => done(e));
  446. });
  447. });
  448. });
  449. describe('window.alert(message, title)', () => {
  450. it('throws an exception when the arguments cannot be converted to strings', () => {
  451. expect(() => {
  452. window.alert({ toString: null });
  453. }).to.throw('Cannot convert object to primitive value');
  454. });
  455. });
  456. describe('window.confirm(message, title)', () => {
  457. it('throws an exception when the arguments cannot be converted to strings', () => {
  458. expect(() => {
  459. window.confirm({ toString: null }, 'title');
  460. }).to.throw('Cannot convert object to primitive value');
  461. });
  462. });
  463. describe('window.history', () => {
  464. describe('window.history.go(offset)', () => {
  465. it('throws an exception when the argumnet cannot be converted to a string', () => {
  466. expect(() => {
  467. window.history.go({ toString: null });
  468. }).to.throw('Cannot convert object to primitive value');
  469. });
  470. });
  471. });
  472. // TODO(nornagon): this is broken on CI, it triggers:
  473. // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
  474. // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
  475. // (null text in SpeechSynthesisUtterance struct).
  476. describe.skip('SpeechSynthesis', () => {
  477. before(function () {
  478. if (!features.isTtsEnabled()) {
  479. this.skip();
  480. }
  481. });
  482. it('should emit lifecycle events', async () => {
  483. const sentence = `long sentence which will take at least a few seconds to
  484. utter so that it's possible to pause and resume before the end`;
  485. const utter = new SpeechSynthesisUtterance(sentence);
  486. // Create a dummy utterence so that speech synthesis state
  487. // is initialized for later calls.
  488. speechSynthesis.speak(new SpeechSynthesisUtterance());
  489. speechSynthesis.cancel();
  490. speechSynthesis.speak(utter);
  491. // paused state after speak()
  492. expect(speechSynthesis.paused).to.be.false();
  493. await new Promise((resolve) => { utter.onstart = resolve; });
  494. // paused state after start event
  495. expect(speechSynthesis.paused).to.be.false();
  496. speechSynthesis.pause();
  497. // paused state changes async, right before the pause event
  498. expect(speechSynthesis.paused).to.be.false();
  499. await new Promise((resolve) => { utter.onpause = resolve; });
  500. expect(speechSynthesis.paused).to.be.true();
  501. speechSynthesis.resume();
  502. await new Promise((resolve) => { utter.onresume = resolve; });
  503. // paused state after resume event
  504. expect(speechSynthesis.paused).to.be.false();
  505. await new Promise((resolve) => { utter.onend = resolve; });
  506. });
  507. });
  508. });
  509. describe('console functions', () => {
  510. it('should exist', () => {
  511. expect(console.log, 'log').to.be.a('function');
  512. expect(console.error, 'error').to.be.a('function');
  513. expect(console.warn, 'warn').to.be.a('function');
  514. expect(console.info, 'info').to.be.a('function');
  515. expect(console.debug, 'debug').to.be.a('function');
  516. expect(console.trace, 'trace').to.be.a('function');
  517. expect(console.time, 'time').to.be.a('function');
  518. expect(console.timeEnd, 'timeEnd').to.be.a('function');
  519. });
  520. });