chromium-spec.js 19 KB

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