chromium-spec.js 19 KB

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