electron/spec-main/api-browser-window-spec.ts

4042 lines
141 KiB
TypeScript
Raw Normal View History

2020-03-20 20:28:31 +00:00
import { expect } from 'chai';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import * as qs from 'querystring';
import * as http from 'http';
import { AddressInfo } from 'net';
import { app, BrowserWindow, BrowserView, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents } from 'electron';
2020-03-20 20:28:31 +00:00
import { emittedOnce } from './events-helpers';
import { ifit, ifdescribe } from './spec-helpers';
import { closeWindow, closeAllWindows } from './window-helpers';
2020-03-20 20:28:31 +00:00
const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures');
// Is the display's scale factor possibly causing rounding of pixel coordinate
// values?
const isScaleFactorRounding = () => {
2020-03-20 20:28:31 +00:00
const { scaleFactor } = screen.getPrimaryDisplay();
// Return true if scale factor is non-integer value
2020-03-20 20:28:31 +00:00
if (Math.round(scaleFactor) !== scaleFactor) return true;
// Return true if scale factor is odd number above 2
2020-03-20 20:28:31 +00:00
return scaleFactor > 2 && scaleFactor % 2 === 1;
};
const expectBoundsEqual = (actual: any, expected: any) => {
if (!isScaleFactorRounding()) {
2020-03-20 20:28:31 +00:00
expect(expected).to.deep.equal(actual);
} else if (Array.isArray(actual)) {
2020-03-20 20:28:31 +00:00
expect(actual[0]).to.be.closeTo(expected[0], 1);
expect(actual[1]).to.be.closeTo(expected[1], 1);
} else {
2020-03-20 20:28:31 +00:00
expect(actual.x).to.be.closeTo(expected.x, 1);
expect(actual.y).to.be.closeTo(expected.y, 1);
expect(actual.width).to.be.closeTo(expected.width, 1);
expect(actual.height).to.be.closeTo(expected.height, 1);
}
2020-03-20 20:28:31 +00:00
};
describe('BrowserWindow module', () => {
describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', async () => {
expect(() => {
const w = new BrowserWindow({
show: false,
// apparently void 0 had different behaviour from undefined in the
// issue that this test is supposed to catch.
webContents: void 0 // eslint-disable-line no-void
2020-03-20 20:28:31 +00:00
} as any);
w.destroy();
}).not.to.throw();
});
});
describe('garbage collection', () => {
2020-03-20 20:28:31 +00:00
const v8Util = process.electronBinding('v8_util');
afterEach(closeAllWindows);
it('window does not get garbage collected when opened', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
// Keep a weak reference to the window.
2020-03-20 20:28:31 +00:00
const map = v8Util.createIDWeakMap<Electron.BrowserWindow>();
map.set(0, w);
setTimeout(() => {
// Do garbage collection, since |w| is not referenced in this closure
// it would be gone after next call if there is no other reference.
2020-03-20 20:28:31 +00:00
v8Util.requestGarbageCollectionForTesting();
setTimeout(() => {
2020-03-20 20:28:31 +00:00
expect(map.has(0)).to.equal(true);
done();
});
});
});
});
describe('BrowserWindow.close()', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should emit unload handler', async () => {
2020-03-20 20:28:31 +00:00
await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
const closed = emittedOnce(w, 'closed');
w.close();
await closed;
const test = path.join(fixtures, 'api', 'unload');
const content = fs.readFileSync(test);
fs.unlinkSync(test);
expect(String(content)).to.equal('unload');
});
it('should emit beforeunload handler', async () => {
2020-03-20 20:28:31 +00:00
await w.loadFile(path.join(fixtures, 'api', 'beforeunload-false.html'));
const beforeunload = new Promise(resolve => {
ipcMain.once('onbeforeunload', (e) => {
2020-03-20 20:28:31 +00:00
e.returnValue = null;
resolve();
});
});
w.close();
await beforeunload;
});
describe('when invoked synchronously inside navigation observer', () => {
2020-03-20 20:28:31 +00:00
let server: http.Server = null as unknown as http.Server;
let url: string = null as unknown as string;
before((done) => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
2020-03-20 20:28:31 +00:00
response.destroy();
break;
case '/301':
2020-03-20 20:28:31 +00:00
response.statusCode = 301;
response.setHeader('Location', '/200');
response.end();
break;
case '/200':
2020-03-20 20:28:31 +00:00
response.statusCode = 200;
response.end('hello');
break;
case '/title':
2020-03-20 20:28:31 +00:00
response.statusCode = 200;
response.end('<title>Hello</title>');
break;
default:
2020-03-20 20:28:31 +00:00
throw new Error(`unsupported endpoint: ${request.url}`);
}
}).listen(0, '127.0.0.1', () => {
2020-03-20 20:28:31 +00:00
url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
done();
});
});
after(() => {
2020-03-20 20:28:31 +00:00
server.close();
});
const events = [
{ name: 'did-start-loading', path: '/200' },
{ name: 'dom-ready', path: '/200' },
{ name: 'page-title-updated', path: '/title' },
{ name: 'did-stop-loading', path: '/200' },
{ name: 'did-finish-load', path: '/200' },
{ name: 'did-frame-finish-load', path: '/200' },
{ name: 'did-fail-load', path: '/net-error' }
2020-03-20 20:28:31 +00:00
];
2019-11-01 20:37:02 +00:00
for (const { name, path } of events) {
it(`should not crash when closed during ${name}`, async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.once((name as any), () => {
2020-03-20 20:28:31 +00:00
w.close();
});
const destroyed = emittedOnce(w.webContents, 'destroyed');
w.webContents.loadURL(url + path);
await destroyed;
});
}
2020-03-20 20:28:31 +00:00
});
});
describe('window.close()', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should emit unload event', async () => {
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(fixtures, 'api', 'close.html'));
await emittedOnce(w, 'closed');
const test = path.join(fixtures, 'api', 'close');
const content = fs.readFileSync(test).toString();
fs.unlinkSync(test);
expect(content).to.equal('close');
});
it('should emit beforeunload event', async () => {
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'close-beforeunload-false.html'));
const [e] = await emittedOnce(ipcMain, 'onbeforeunload');
e.returnValue = null;
});
});
describe('BrowserWindow.destroy()', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('prevents users to access methods of webContents', async () => {
2020-03-20 20:28:31 +00:00
const contents = w.webContents;
w.destroy();
await new Promise(setImmediate);
expect(() => {
2020-03-20 20:28:31 +00:00
contents.getProcessId();
}).to.throw('Object has been destroyed');
});
it('should not crash when destroying windows with pending events', () => {
2020-03-20 20:28:31 +00:00
const focusListener = () => { };
app.on('browser-window-focus', focusListener);
const windowCount = 3;
const windowOptions = {
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
2020-03-20 20:28:31 +00:00
};
const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
windows.forEach(win => win.show());
windows.forEach(win => win.focus());
windows.forEach(win => win.destroy());
app.removeListener('browser-window-focus', focusListener);
});
});
describe('BrowserWindow.loadURL(url)', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
const scheme = 'other';
const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
chore: bump chromium to f1d9522c04ca8fa0a906f88ababe9 (master) (#18648) * chore: bump chromium in DEPS to 675d7dc9f3334b15c3ec28c27db3dc19b26bd12e * chore: update patches * chore: bump chromium in DEPS to dce3562696f165a324273fcb6893f0e1fef42ab1 * chore: const interfaces are being removed from //content Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1631749 Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=908139 * chore: update patches * chore: blink::MediaStreamType is now consistent and deduplicated * chore: update patches and printing code for ref -> uniq * chore: bridge_impl() --> GetInProcessNSWindowBridge Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1642988 * fixme: TotalMarkedObjectSize has been removed * chore: fix linting * chore: bump chromium in DEPS to 9503e1a2fcbf17db08094d8caae3e1407e918af3 * chore: fix slightly broken printing patch * chore: update patches for SiteInstanceImpl changes Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1612025 * chore: update patches for SiteInstanceImpl changes * chore: bump chromium in DEPS to 6801e6c1ddd1b7b73e594e97157ddd539ca335d7 * chore: update patches * chore: bump chromium in DEPS to 27e198912d7c1767052ec785c22e2e88b2cb4d8b * chore: remove system_request_context Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1647172 * chore: creation of FtpProtocolHandler needs an auth cache Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1639683 * fixme: disable marked spec * chore: bump chromium in DEPS to 3dcd7fe453ad13a22b114b95f05590eba74c5471 * chore: bump chromium in DEPS to bdc24128b75008743d819e298557a53205706e7c * chore: bump chromium in DEPS to 7da330b58fbe0ba94b9b94abbb8085bead220228 * update patches * remove TotalMarkedObjectSize https://chromium-review.googlesource.com/c/chromium/src/+/1631708 * add libvulkan.so to dist zip manifest on linux * chore: bump chromium in DEPS to 1e85d0f45b52649efd0010cc9dab6d2804f24443 * update patches * add angle features to gpuinfo https://chromium-review.googlesource.com/c/chromium/src/+/1638658 * mark 'marked' property as deprecated * disable webview resize test * FIXME: disable vulkan on 32-bit arm * chore: bump chromium in DEPS to cd0297c6a83fdd2b1f6bc312e7d5acca736a3c56 * Revert "FIXME: disable vulkan on 32-bit arm" This reverts commit 5c1e0ef302a6db1e72231d4e823f91bb08e281af. * backport from upstream: fix swiftshader build on arm https://swiftshader-review.googlesource.com/c/SwiftShader/+/32768/ * update patches * viz: update OutputDeviceWin to new shared memory api https://chromium-review.googlesource.com/c/chromium/src/+/1649574 * base::Contains{Key,Value} => base::Contains https://chromium-review.googlesource.com/c/chromium/src/+/1649478 * fixup! viz: update OutputDeviceWin to new shared memory api * stub out StatusIconLinuxDbus-related delegate methods https://chromium-review.googlesource.com/c/chromium/src/+/1638180 * chore: bump chromium in DEPS to 964ea3fd4bdc006d62533f5755043076220181f1 * Remove the BrowserContext methods to create URLRequestContexts for main/media partitions when a partition_domain is specified https://chromium-review.googlesource.com/c/chromium/src/+/1655087 * fixup! stub out StatusIconLinuxDbus-related delegate methods * add remote_cocoa to chromium_src deps https://chromium-review.googlesource.com/c/chromium/src/+/1657068 * fixup! stub out StatusIconLinuxDbus-related delegate methods * attempt at fix linux-debug build * add swiftshader/libvulkan.so to arm manifest * chore: bump chromium in DEPS to 28688f76afef27c36631aa274691e333ddecdc22 * update patches * chore: bump chromium in DEPS to fe7450e1578a9584189f87d59d0d1a8548bf6b90 * chore: bump chromium in DEPS to f304dfd682dc86a755a6c49a16ee6876e0db45fb * chore: bump chromium in DEPS to f0fd4d6c365aad9edd83bdfff9954c47d271b75c * Update patches * Remove no longer needed WOA patch * Put back IOThread in BrowserProcess We need this until we enable the network service. * move atom.ico to inputs * Update to latest LKGR to fix no template named 'bitset' in namespace 'std' * fixup! Put back IOThread in BrowserProcess * chore: bump chromium in DEPS to dcf9662dc9a896a175d791001350324167b1cad3 * Update patches content_allow_embedder_to_prevent_locking_scheme_registry.patch is no longer necessary as it was upstreamed via https://chromium-review.googlesource.com/c/chromium/src/+/1637040 * Fix renamed enum * Use newer docker container Contains updated dependencies * Try to track down arm test failures * Fix arm tests * chore: bump chromium in DEPS to 8cbceef57b37ee14b9c4c3405a3f7663922c5b5d * Update patches * Add needed dependencies for testing 32-bit linux * Remove arm debugging. * Remove additional debugging * Fix compiler errors * Handle new macOS helper * Fix compile error on Linux * chore: bump chromium in DEPS to 66a93991ddaff6a9f1b13d110959947cb03a1860 * Add new helper files to manifests * fix BUILD.gn for macOS * Fix compile errors * Add patch to put back colors needed for autofill/datalist * chore: bump chromium in DEPS to e89617079f11e33f33cdb3924f719a579c73704b * Updated patches * Remove no longer needed patch * Remove no longer needed patch * Fix compile error with patch * Really fix the patch * chore: bump chromium in DEPS to c70f12476a45840408f1d5ff5968e7f7ceaad9d4 * chore: bump chromium in DEPS to 06d2dd7a8933b41545a7c26349c802f570563fd5 * chore: bump chromium in DEPS to b0b9ff8f727deb519ccbec7cf1c8d9ed543d88ab * Update patches * Fix compiler errors * Fix removed ChromeNetLog * Revert "Fix removed ChromeNetLog" This reverts commit 426dfd90b5ab0a9c1df415d71c88e8aed2bd5bbe. * Remove ChromeNetLog. https://chromium-review.googlesource.com/c/chromium/src/+/1663846 * chore: bump chromium in DEPS to fefcc4926d58dccd59ac95be65eab3a4ebfe2f29 * Update patches * Update v8 patches * Fix lint error * Fix compile errors * chore: bump chromium in DEPS to 4de815ef92ef2eef515506fe09bdc466526a8fd9 * Use custom protocol to test baseURLForDataURL * Use newer SDK (10.0.18362) for Windows * Update patches * Update arm manifest since swiftshader reenabled. * Don't delete dir that isn't ever there. * Fix compile errors. * Need src dir created * Update for removed InspectorFrontendAPI.addExtensions * Revert "Use newer SDK (10.0.18362) for Windows" This reverts commit 68763a0c88cdc44b971462e49662aecc167d3d99. * Revert "Need src dir created" This reverts commit 7daedc29d0844316d4097648dde7f40f1a3848fb. * Revert "Don't delete dir that isn't ever there." This reverts commit bf424bc30ffcb23b1d9a634d4df410342536640e. * chore: bump chromium in DEPS to 97dab6b0124ea53244caf123921b5d14893bcca7 * chore: bump chromium in DEPS to c87d16d49a85dc7122781f6c979d354c20f7f78b * chore: bump chromium in DEPS to 004bcee2ea336687cedfda8f8a151806ac757d15 * chore: bump chromium in DEPS to 24428b26a9d15a013b2a253e1084ec3cb54b660b * chore: bump chromium in DEPS to fd25914e875237df88035a6abf89a70bf1360b57 * Update patches * Update node to fix build error * Fix compile errors * chore: bump chromium in DEPS to 3062b7cf090f1d9522c04ca8fa0a906f88ababe9 * chore: update node ref for pushed tags * chore: update patches for new chromium * chore: fix printing patches * Use new (10.0.18362) Windows SDK * roll node to fix v8 build issues in debug build * Add support for plugin helper * fix: add patch to fix gpu info enumeration Can be removed once CL lands upstream. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1685993 * spec: navigator.requestMIDIAccess now requires a secure origin This test requires a secure origin so we fake one. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1657952 * FIXME: temporarily disable SharedWorker tests * use released version of node-abstractsocket * fix abstract-socket
2019-07-03 01:22:09 +00:00
before((done) => {
protocol.registerFileProtocol(scheme, (request, callback) => {
2020-03-20 20:28:31 +00:00
callback(srcPath);
}, (error) => done(error));
});
chore: bump chromium to f1d9522c04ca8fa0a906f88ababe9 (master) (#18648) * chore: bump chromium in DEPS to 675d7dc9f3334b15c3ec28c27db3dc19b26bd12e * chore: update patches * chore: bump chromium in DEPS to dce3562696f165a324273fcb6893f0e1fef42ab1 * chore: const interfaces are being removed from //content Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1631749 Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=908139 * chore: update patches * chore: blink::MediaStreamType is now consistent and deduplicated * chore: update patches and printing code for ref -> uniq * chore: bridge_impl() --> GetInProcessNSWindowBridge Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1642988 * fixme: TotalMarkedObjectSize has been removed * chore: fix linting * chore: bump chromium in DEPS to 9503e1a2fcbf17db08094d8caae3e1407e918af3 * chore: fix slightly broken printing patch * chore: update patches for SiteInstanceImpl changes Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1612025 * chore: update patches for SiteInstanceImpl changes * chore: bump chromium in DEPS to 6801e6c1ddd1b7b73e594e97157ddd539ca335d7 * chore: update patches * chore: bump chromium in DEPS to 27e198912d7c1767052ec785c22e2e88b2cb4d8b * chore: remove system_request_context Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1647172 * chore: creation of FtpProtocolHandler needs an auth cache Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1639683 * fixme: disable marked spec * chore: bump chromium in DEPS to 3dcd7fe453ad13a22b114b95f05590eba74c5471 * chore: bump chromium in DEPS to bdc24128b75008743d819e298557a53205706e7c * chore: bump chromium in DEPS to 7da330b58fbe0ba94b9b94abbb8085bead220228 * update patches * remove TotalMarkedObjectSize https://chromium-review.googlesource.com/c/chromium/src/+/1631708 * add libvulkan.so to dist zip manifest on linux * chore: bump chromium in DEPS to 1e85d0f45b52649efd0010cc9dab6d2804f24443 * update patches * add angle features to gpuinfo https://chromium-review.googlesource.com/c/chromium/src/+/1638658 * mark 'marked' property as deprecated * disable webview resize test * FIXME: disable vulkan on 32-bit arm * chore: bump chromium in DEPS to cd0297c6a83fdd2b1f6bc312e7d5acca736a3c56 * Revert "FIXME: disable vulkan on 32-bit arm" This reverts commit 5c1e0ef302a6db1e72231d4e823f91bb08e281af. * backport from upstream: fix swiftshader build on arm https://swiftshader-review.googlesource.com/c/SwiftShader/+/32768/ * update patches * viz: update OutputDeviceWin to new shared memory api https://chromium-review.googlesource.com/c/chromium/src/+/1649574 * base::Contains{Key,Value} => base::Contains https://chromium-review.googlesource.com/c/chromium/src/+/1649478 * fixup! viz: update OutputDeviceWin to new shared memory api * stub out StatusIconLinuxDbus-related delegate methods https://chromium-review.googlesource.com/c/chromium/src/+/1638180 * chore: bump chromium in DEPS to 964ea3fd4bdc006d62533f5755043076220181f1 * Remove the BrowserContext methods to create URLRequestContexts for main/media partitions when a partition_domain is specified https://chromium-review.googlesource.com/c/chromium/src/+/1655087 * fixup! stub out StatusIconLinuxDbus-related delegate methods * add remote_cocoa to chromium_src deps https://chromium-review.googlesource.com/c/chromium/src/+/1657068 * fixup! stub out StatusIconLinuxDbus-related delegate methods * attempt at fix linux-debug build * add swiftshader/libvulkan.so to arm manifest * chore: bump chromium in DEPS to 28688f76afef27c36631aa274691e333ddecdc22 * update patches * chore: bump chromium in DEPS to fe7450e1578a9584189f87d59d0d1a8548bf6b90 * chore: bump chromium in DEPS to f304dfd682dc86a755a6c49a16ee6876e0db45fb * chore: bump chromium in DEPS to f0fd4d6c365aad9edd83bdfff9954c47d271b75c * Update patches * Remove no longer needed WOA patch * Put back IOThread in BrowserProcess We need this until we enable the network service. * move atom.ico to inputs * Update to latest LKGR to fix no template named 'bitset' in namespace 'std' * fixup! Put back IOThread in BrowserProcess * chore: bump chromium in DEPS to dcf9662dc9a896a175d791001350324167b1cad3 * Update patches content_allow_embedder_to_prevent_locking_scheme_registry.patch is no longer necessary as it was upstreamed via https://chromium-review.googlesource.com/c/chromium/src/+/1637040 * Fix renamed enum * Use newer docker container Contains updated dependencies * Try to track down arm test failures * Fix arm tests * chore: bump chromium in DEPS to 8cbceef57b37ee14b9c4c3405a3f7663922c5b5d * Update patches * Add needed dependencies for testing 32-bit linux * Remove arm debugging. * Remove additional debugging * Fix compiler errors * Handle new macOS helper * Fix compile error on Linux * chore: bump chromium in DEPS to 66a93991ddaff6a9f1b13d110959947cb03a1860 * Add new helper files to manifests * fix BUILD.gn for macOS * Fix compile errors * Add patch to put back colors needed for autofill/datalist * chore: bump chromium in DEPS to e89617079f11e33f33cdb3924f719a579c73704b * Updated patches * Remove no longer needed patch * Remove no longer needed patch * Fix compile error with patch * Really fix the patch * chore: bump chromium in DEPS to c70f12476a45840408f1d5ff5968e7f7ceaad9d4 * chore: bump chromium in DEPS to 06d2dd7a8933b41545a7c26349c802f570563fd5 * chore: bump chromium in DEPS to b0b9ff8f727deb519ccbec7cf1c8d9ed543d88ab * Update patches * Fix compiler errors * Fix removed ChromeNetLog * Revert "Fix removed ChromeNetLog" This reverts commit 426dfd90b5ab0a9c1df415d71c88e8aed2bd5bbe. * Remove ChromeNetLog. https://chromium-review.googlesource.com/c/chromium/src/+/1663846 * chore: bump chromium in DEPS to fefcc4926d58dccd59ac95be65eab3a4ebfe2f29 * Update patches * Update v8 patches * Fix lint error * Fix compile errors * chore: bump chromium in DEPS to 4de815ef92ef2eef515506fe09bdc466526a8fd9 * Use custom protocol to test baseURLForDataURL * Use newer SDK (10.0.18362) for Windows * Update patches * Update arm manifest since swiftshader reenabled. * Don't delete dir that isn't ever there. * Fix compile errors. * Need src dir created * Update for removed InspectorFrontendAPI.addExtensions * Revert "Use newer SDK (10.0.18362) for Windows" This reverts commit 68763a0c88cdc44b971462e49662aecc167d3d99. * Revert "Need src dir created" This reverts commit 7daedc29d0844316d4097648dde7f40f1a3848fb. * Revert "Don't delete dir that isn't ever there." This reverts commit bf424bc30ffcb23b1d9a634d4df410342536640e. * chore: bump chromium in DEPS to 97dab6b0124ea53244caf123921b5d14893bcca7 * chore: bump chromium in DEPS to c87d16d49a85dc7122781f6c979d354c20f7f78b * chore: bump chromium in DEPS to 004bcee2ea336687cedfda8f8a151806ac757d15 * chore: bump chromium in DEPS to 24428b26a9d15a013b2a253e1084ec3cb54b660b * chore: bump chromium in DEPS to fd25914e875237df88035a6abf89a70bf1360b57 * Update patches * Update node to fix build error * Fix compile errors * chore: bump chromium in DEPS to 3062b7cf090f1d9522c04ca8fa0a906f88ababe9 * chore: update node ref for pushed tags * chore: update patches for new chromium * chore: fix printing patches * Use new (10.0.18362) Windows SDK * roll node to fix v8 build issues in debug build * Add support for plugin helper * fix: add patch to fix gpu info enumeration Can be removed once CL lands upstream. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1685993 * spec: navigator.requestMIDIAccess now requires a secure origin This test requires a secure origin so we fake one. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1657952 * FIXME: temporarily disable SharedWorker tests * use released version of node-abstractsocket * fix abstract-socket
2019-07-03 01:22:09 +00:00
after(() => {
2020-03-20 20:28:31 +00:00
protocol.unregisterProtocol(scheme);
});
chore: bump chromium to f1d9522c04ca8fa0a906f88ababe9 (master) (#18648) * chore: bump chromium in DEPS to 675d7dc9f3334b15c3ec28c27db3dc19b26bd12e * chore: update patches * chore: bump chromium in DEPS to dce3562696f165a324273fcb6893f0e1fef42ab1 * chore: const interfaces are being removed from //content Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1631749 Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=908139 * chore: update patches * chore: blink::MediaStreamType is now consistent and deduplicated * chore: update patches and printing code for ref -> uniq * chore: bridge_impl() --> GetInProcessNSWindowBridge Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1642988 * fixme: TotalMarkedObjectSize has been removed * chore: fix linting * chore: bump chromium in DEPS to 9503e1a2fcbf17db08094d8caae3e1407e918af3 * chore: fix slightly broken printing patch * chore: update patches for SiteInstanceImpl changes Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1612025 * chore: update patches for SiteInstanceImpl changes * chore: bump chromium in DEPS to 6801e6c1ddd1b7b73e594e97157ddd539ca335d7 * chore: update patches * chore: bump chromium in DEPS to 27e198912d7c1767052ec785c22e2e88b2cb4d8b * chore: remove system_request_context Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1647172 * chore: creation of FtpProtocolHandler needs an auth cache Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1639683 * fixme: disable marked spec * chore: bump chromium in DEPS to 3dcd7fe453ad13a22b114b95f05590eba74c5471 * chore: bump chromium in DEPS to bdc24128b75008743d819e298557a53205706e7c * chore: bump chromium in DEPS to 7da330b58fbe0ba94b9b94abbb8085bead220228 * update patches * remove TotalMarkedObjectSize https://chromium-review.googlesource.com/c/chromium/src/+/1631708 * add libvulkan.so to dist zip manifest on linux * chore: bump chromium in DEPS to 1e85d0f45b52649efd0010cc9dab6d2804f24443 * update patches * add angle features to gpuinfo https://chromium-review.googlesource.com/c/chromium/src/+/1638658 * mark 'marked' property as deprecated * disable webview resize test * FIXME: disable vulkan on 32-bit arm * chore: bump chromium in DEPS to cd0297c6a83fdd2b1f6bc312e7d5acca736a3c56 * Revert "FIXME: disable vulkan on 32-bit arm" This reverts commit 5c1e0ef302a6db1e72231d4e823f91bb08e281af. * backport from upstream: fix swiftshader build on arm https://swiftshader-review.googlesource.com/c/SwiftShader/+/32768/ * update patches * viz: update OutputDeviceWin to new shared memory api https://chromium-review.googlesource.com/c/chromium/src/+/1649574 * base::Contains{Key,Value} => base::Contains https://chromium-review.googlesource.com/c/chromium/src/+/1649478 * fixup! viz: update OutputDeviceWin to new shared memory api * stub out StatusIconLinuxDbus-related delegate methods https://chromium-review.googlesource.com/c/chromium/src/+/1638180 * chore: bump chromium in DEPS to 964ea3fd4bdc006d62533f5755043076220181f1 * Remove the BrowserContext methods to create URLRequestContexts for main/media partitions when a partition_domain is specified https://chromium-review.googlesource.com/c/chromium/src/+/1655087 * fixup! stub out StatusIconLinuxDbus-related delegate methods * add remote_cocoa to chromium_src deps https://chromium-review.googlesource.com/c/chromium/src/+/1657068 * fixup! stub out StatusIconLinuxDbus-related delegate methods * attempt at fix linux-debug build * add swiftshader/libvulkan.so to arm manifest * chore: bump chromium in DEPS to 28688f76afef27c36631aa274691e333ddecdc22 * update patches * chore: bump chromium in DEPS to fe7450e1578a9584189f87d59d0d1a8548bf6b90 * chore: bump chromium in DEPS to f304dfd682dc86a755a6c49a16ee6876e0db45fb * chore: bump chromium in DEPS to f0fd4d6c365aad9edd83bdfff9954c47d271b75c * Update patches * Remove no longer needed WOA patch * Put back IOThread in BrowserProcess We need this until we enable the network service. * move atom.ico to inputs * Update to latest LKGR to fix no template named 'bitset' in namespace 'std' * fixup! Put back IOThread in BrowserProcess * chore: bump chromium in DEPS to dcf9662dc9a896a175d791001350324167b1cad3 * Update patches content_allow_embedder_to_prevent_locking_scheme_registry.patch is no longer necessary as it was upstreamed via https://chromium-review.googlesource.com/c/chromium/src/+/1637040 * Fix renamed enum * Use newer docker container Contains updated dependencies * Try to track down arm test failures * Fix arm tests * chore: bump chromium in DEPS to 8cbceef57b37ee14b9c4c3405a3f7663922c5b5d * Update patches * Add needed dependencies for testing 32-bit linux * Remove arm debugging. * Remove additional debugging * Fix compiler errors * Handle new macOS helper * Fix compile error on Linux * chore: bump chromium in DEPS to 66a93991ddaff6a9f1b13d110959947cb03a1860 * Add new helper files to manifests * fix BUILD.gn for macOS * Fix compile errors * Add patch to put back colors needed for autofill/datalist * chore: bump chromium in DEPS to e89617079f11e33f33cdb3924f719a579c73704b * Updated patches * Remove no longer needed patch * Remove no longer needed patch * Fix compile error with patch * Really fix the patch * chore: bump chromium in DEPS to c70f12476a45840408f1d5ff5968e7f7ceaad9d4 * chore: bump chromium in DEPS to 06d2dd7a8933b41545a7c26349c802f570563fd5 * chore: bump chromium in DEPS to b0b9ff8f727deb519ccbec7cf1c8d9ed543d88ab * Update patches * Fix compiler errors * Fix removed ChromeNetLog * Revert "Fix removed ChromeNetLog" This reverts commit 426dfd90b5ab0a9c1df415d71c88e8aed2bd5bbe. * Remove ChromeNetLog. https://chromium-review.googlesource.com/c/chromium/src/+/1663846 * chore: bump chromium in DEPS to fefcc4926d58dccd59ac95be65eab3a4ebfe2f29 * Update patches * Update v8 patches * Fix lint error * Fix compile errors * chore: bump chromium in DEPS to 4de815ef92ef2eef515506fe09bdc466526a8fd9 * Use custom protocol to test baseURLForDataURL * Use newer SDK (10.0.18362) for Windows * Update patches * Update arm manifest since swiftshader reenabled. * Don't delete dir that isn't ever there. * Fix compile errors. * Need src dir created * Update for removed InspectorFrontendAPI.addExtensions * Revert "Use newer SDK (10.0.18362) for Windows" This reverts commit 68763a0c88cdc44b971462e49662aecc167d3d99. * Revert "Need src dir created" This reverts commit 7daedc29d0844316d4097648dde7f40f1a3848fb. * Revert "Don't delete dir that isn't ever there." This reverts commit bf424bc30ffcb23b1d9a634d4df410342536640e. * chore: bump chromium in DEPS to 97dab6b0124ea53244caf123921b5d14893bcca7 * chore: bump chromium in DEPS to c87d16d49a85dc7122781f6c979d354c20f7f78b * chore: bump chromium in DEPS to 004bcee2ea336687cedfda8f8a151806ac757d15 * chore: bump chromium in DEPS to 24428b26a9d15a013b2a253e1084ec3cb54b660b * chore: bump chromium in DEPS to fd25914e875237df88035a6abf89a70bf1360b57 * Update patches * Update node to fix build error * Fix compile errors * chore: bump chromium in DEPS to 3062b7cf090f1d9522c04ca8fa0a906f88ababe9 * chore: update node ref for pushed tags * chore: update patches for new chromium * chore: fix printing patches * Use new (10.0.18362) Windows SDK * roll node to fix v8 build issues in debug build * Add support for plugin helper * fix: add patch to fix gpu info enumeration Can be removed once CL lands upstream. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1685993 * spec: navigator.requestMIDIAccess now requires a secure origin This test requires a secure origin so we fake one. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1657952 * FIXME: temporarily disable SharedWorker tests * use released version of node-abstractsocket * fix abstract-socket
2019-07-03 01:22:09 +00:00
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
let server = null as unknown as http.Server;
let url = null as unknown as string;
let postData = null as any;
before((done) => {
2020-03-20 20:28:31 +00:00
const filePath = path.join(fixtures, 'pages', 'a.html');
const fileStats = fs.statSync(filePath);
postData = [
{
type: 'rawData',
bytes: Buffer.from('username=test&file=')
},
{
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
}
2020-03-20 20:28:31 +00:00
];
server = http.createServer((req, res) => {
function respond () {
if (req.method === 'POST') {
2020-03-20 20:28:31 +00:00
let body = '';
req.on('data', (data) => {
2020-03-20 20:28:31 +00:00
if (data) body += data;
});
req.on('end', () => {
2020-03-20 20:28:31 +00:00
const parsedData = qs.parse(body);
fs.readFile(filePath, (err, data) => {
2020-03-20 20:28:31 +00:00
if (err) return;
if (parsedData.username === 'test' &&
parsedData.file === data.toString()) {
2020-03-20 20:28:31 +00:00
res.end();
}
2020-03-20 20:28:31 +00:00
});
});
} else if (req.url === '/302') {
2020-03-20 20:28:31 +00:00
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
2020-03-20 20:28:31 +00:00
res.end();
}
}
2020-03-20 20:28:31 +00:00
setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0);
});
server.listen(0, '127.0.0.1', () => {
2020-03-20 20:28:31 +00:00
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
done();
});
});
after(() => {
2020-03-20 20:28:31 +00:00
server.close();
});
it('should emit did-start-loading event', (done) => {
2020-03-20 20:28:31 +00:00
w.webContents.on('did-start-loading', () => { done(); });
w.loadURL('about:blank');
});
it('should emit ready-to-show event', (done) => {
2020-03-20 20:28:31 +00:00
w.on('ready-to-show', () => { done(); });
w.loadURL('about:blank');
});
// TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
// changed and adjust the test.
it.skip('should emit did-fail-load event for files that do not exist', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
2020-03-20 20:28:31 +00:00
expect(code).to.equal(-6);
expect(desc).to.equal('ERR_FILE_NOT_FOUND');
expect(isMainFrame).to.equal(true);
done();
});
w.loadURL('file://a.txt');
});
it('should emit did-fail-load event for invalid URL', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
2020-03-20 20:28:31 +00:00
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
done();
});
w.loadURL('http://example:port');
});
it('should set `mainFrame = false` on did-fail-load events in iframes', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
2020-03-20 20:28:31 +00:00
expect(isMainFrame).to.equal(false);
done();
});
w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
});
it('does not crash in did-fail-provisional-load handler', (done) => {
w.webContents.once('did-fail-provisional-load', () => {
2020-03-20 20:28:31 +00:00
w.loadURL('http://127.0.0.1:11111');
done();
});
w.loadURL('http://127.0.0.1:11111');
});
it('should emit did-fail-load event for URL exceeding character limit', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
2020-03-20 20:28:31 +00:00
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
done();
});
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
w.loadURL(`data:image/png;base64,${data}`);
});
it('should return a promise', () => {
2020-03-20 20:28:31 +00:00
const p = w.loadURL('about:blank');
expect(p).to.have.property('then');
});
it('should return a promise that resolves', async () => {
2020-03-20 20:28:31 +00:00
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('should return a promise that rejects on a load failure', async () => {
2020-03-20 20:28:31 +00:00
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const p = w.loadURL(`data:image/png;base64,${data}`);
await expect(p).to.eventually.be.rejected;
});
it('should return a promise that resolves even if pushState occurs during navigation', async () => {
2020-03-20 20:28:31 +00:00
const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
await expect(p).to.eventually.be.fulfilled;
});
// FIXME(robo/nornagon): re-enable these once service workers work
describe.skip('POST navigations', () => {
2020-03-20 20:28:31 +00:00
afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
it('supports specifying POST data', async () => {
2020-03-20 20:28:31 +00:00
await w.loadURL(url, { postData });
});
it('sets the content type header on URL encoded forms', async () => {
2020-03-20 20:28:31 +00:00
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
2019-11-01 20:37:02 +00:00
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
2020-03-20 20:28:31 +00:00
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.submit()
2020-03-20 20:28:31 +00:00
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
});
it('sets the content type header on multi part forms', async () => {
2020-03-20 20:28:31 +00:00
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
2019-11-01 20:37:02 +00:00
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
2020-03-20 20:28:31 +00:00
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
2020-03-20 20:28:31 +00:00
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
});
});
it('should support support base url for data urls', (done) => {
ipcMain.once('answer', (event, test) => {
2020-03-20 20:28:31 +00:00
expect(test).to.equal('test');
done();
});
w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
});
});
for (const sandbox of [false, true]) {
describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('will-navigate event', () => {
2020-03-20 20:28:31 +00:00
let server = null as unknown as http.Server;
let url = null as unknown as string;
before((done) => {
2020-03-20 20:28:31 +00:00
server = http.createServer((req, res) => { res.end(''); });
server.listen(0, '127.0.0.1', () => {
2020-03-20 20:28:31 +00:00
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
after(() => {
2020-03-20 20:28:31 +00:00
server.close();
});
it('allows the window to be closed from the event listener', (done) => {
w.webContents.once('will-navigate', () => {
2020-03-20 20:28:31 +00:00
w.close();
done();
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented', (done) => {
2020-03-20 20:28:31 +00:00
let willNavigate = false;
w.webContents.once('will-navigate', (e) => {
2020-03-20 20:28:31 +00:00
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
2020-03-20 20:28:31 +00:00
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('is triggered when navigating from file: to http:', async () => {
2020-03-20 20:28:31 +00:00
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
2020-03-20 20:28:31 +00:00
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
2020-03-20 20:28:31 +00:00
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
2020-03-20 20:28:31 +00:00
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.equal('about:blank');
});
});
describe('will-redirect event', () => {
2020-03-20 20:28:31 +00:00
let server = null as unknown as http.Server;
let url = null as unknown as string;
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/302') {
2020-03-20 20:28:31 +00:00
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else if (req.url === '/navigate-302') {
2020-03-20 20:28:31 +00:00
res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
} else {
2020-03-20 20:28:31 +00:00
res.end();
}
2020-03-20 20:28:31 +00:00
});
server.listen(0, '127.0.0.1', () => {
2020-03-20 20:28:31 +00:00
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
done();
});
});
after(() => {
2020-03-20 20:28:31 +00:00
server.close();
});
it('is emitted on redirects', (done) => {
w.webContents.on('will-redirect', () => {
2020-03-20 20:28:31 +00:00
done();
});
w.loadURL(`${url}/302`);
});
it('is emitted after will-navigate on redirects', (done) => {
2020-03-20 20:28:31 +00:00
let navigateCalled = false;
w.webContents.on('will-navigate', () => {
2020-03-20 20:28:31 +00:00
navigateCalled = true;
});
w.webContents.on('will-redirect', () => {
2020-03-20 20:28:31 +00:00
expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
done();
});
w.loadURL(`${url}/navigate-302`);
});
it('is emitted before did-stop-loading on redirects', (done) => {
2020-03-20 20:28:31 +00:00
let stopCalled = false;
w.webContents.on('did-stop-loading', () => {
2020-03-20 20:28:31 +00:00
stopCalled = true;
});
w.webContents.on('will-redirect', () => {
2020-03-20 20:28:31 +00:00
expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
done();
});
w.loadURL(`${url}/302`);
});
it('allows the window to be closed from the event listener', (done) => {
w.webContents.once('will-redirect', () => {
2020-03-20 20:28:31 +00:00
w.close();
done();
});
w.loadURL(`${url}/302`);
});
it('can be prevented', (done) => {
w.webContents.once('will-redirect', (event) => {
2020-03-20 20:28:31 +00:00
event.preventDefault();
});
w.webContents.on('will-navigate', (e, u) => {
2020-03-20 20:28:31 +00:00
expect(u).to.equal(`${url}/302`);
});
w.webContents.on('did-stop-loading', () => {
expect(w.webContents.getURL()).to.equal(
`${url}/navigate-302`,
'url should not have changed after navigation event'
2020-03-20 20:28:31 +00:00
);
done();
});
w.webContents.on('will-redirect', (e, u) => {
2020-03-20 20:28:31 +00:00
expect(u).to.equal(`${url}/200`);
});
w.loadURL(`${url}/navigate-302`);
});
});
});
}
describe('focus and visibility', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.show()', () => {
it('should focus on window', () => {
2020-03-20 20:28:31 +00:00
w.show();
expect(w.isFocused()).to.equal(true);
});
it('should make the window visible', () => {
2020-03-20 20:28:31 +00:00
w.show();
expect(w.isVisible()).to.equal(true);
});
it('emits when window is shown', (done) => {
w.once('show', () => {
2020-03-20 20:28:31 +00:00
expect(w.isVisible()).to.equal(true);
done();
});
w.show();
});
});
describe('BrowserWindow.hide()', () => {
it('should defocus on window', () => {
2020-03-20 20:28:31 +00:00
w.hide();
expect(w.isFocused()).to.equal(false);
});
it('should make the window not visible', () => {
2020-03-20 20:28:31 +00:00
w.show();
w.hide();
expect(w.isVisible()).to.equal(false);
});
it('emits when window is hidden', async () => {
2020-03-20 20:28:31 +00:00
const shown = emittedOnce(w, 'show');
w.show();
await shown;
const hidden = emittedOnce(w, 'hide');
w.hide();
await hidden;
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.showInactive()', () => {
it('should not focus on window', () => {
2020-03-20 20:28:31 +00:00
w.showInactive();
expect(w.isFocused()).to.equal(false);
});
});
describe('BrowserWindow.focus()', () => {
it('does not make the window become visible', () => {
2020-03-20 20:28:31 +00:00
expect(w.isVisible()).to.equal(false);
w.focus();
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.blur()', () => {
it('removes focus from window', () => {
2020-03-20 20:28:31 +00:00
w.blur();
expect(w.isFocused()).to.equal(false);
});
});
describe('BrowserWindow.getFocusedWindow()', () => {
it('returns the opener window when dev tools window is focused', async () => {
2020-03-20 20:28:31 +00:00
w.show();
w.webContents.openDevTools({ mode: 'undocked' });
await emittedOnce(w.webContents, 'devtools-focused');
expect(BrowserWindow.getFocusedWindow()).to.equal(w);
});
});
describe('BrowserWindow.moveTop()', () => {
it('should not steal focus', async () => {
2020-03-20 20:28:31 +00:00
const posDelta = 50;
const wShownInactive = emittedOnce(w, 'show');
w.showInactive();
await wShownInactive;
expect(w.isFocused()).to.equal(false);
const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' });
const otherWindowShown = emittedOnce(otherWindow, 'show');
const otherWindowFocused = emittedOnce(otherWindow, 'focus');
otherWindow.show();
await otherWindowShown;
await otherWindowFocused;
expect(otherWindow.isFocused()).to.equal(true);
w.moveTop();
const wPos = w.getPosition();
const wMoving = emittedOnce(w, 'move');
w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta);
await wMoving;
expect(w.isFocused()).to.equal(false);
expect(otherWindow.isFocused()).to.equal(true);
const wFocused = emittedOnce(w, 'focus');
w.focus();
await wFocused;
expect(w.isFocused()).to.equal(true);
otherWindow.moveTop();
const otherWindowPos = otherWindow.getPosition();
const otherWindowMoving = emittedOnce(otherWindow, 'move');
otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta);
await otherWindowMoving;
expect(otherWindow.isFocused()).to.equal(false);
expect(w.isFocused()).to.equal(true);
await closeWindow(otherWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1);
});
});
describe('BrowserWindow.moveAbove(mediaSourceId)', () => {
it('should throw an exception if wrong formatting', async () => {
const fakeSourceIds = [
'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
2020-03-20 20:28:31 +00:00
];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should throw an exception if wrong type', async () => {
2020-03-20 20:28:31 +00:00
const fakeSourceIds = [null as any, 123 as any];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.moveAbove(sourceId);
}).to.throw(/Error processing argument at index 0 */);
});
});
it('should throw an exception if invalid window', async () => {
// It is very unlikely that these window id exist.
const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
2020-03-20 20:28:31 +00:00
'window:123456:9'];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should not throw an exception', async () => {
2020-03-20 20:28:31 +00:00
const w2 = new BrowserWindow({ show: false, title: 'window2' });
const w2Shown = emittedOnce(w2, 'show');
w2.show();
await w2Shown;
expect(() => {
2020-03-20 20:28:31 +00:00
w.moveAbove(w2.getMediaSourceId());
}).to.not.throw();
2020-03-20 20:28:31 +00:00
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.setFocusable()', () => {
it('can set unfocusable window to focusable', async () => {
2020-03-20 20:28:31 +00:00
const w2 = new BrowserWindow({ focusable: false });
const w2Focused = emittedOnce(w2, 'focus');
w2.setFocusable(true);
w2.focus();
await w2Focused;
await closeWindow(w2, { assertNotWindows: false });
});
});
});
describe('sizing', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false, width: 400, height: 400 });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.setBounds(bounds[, animate])', () => {
it('sets the window bounds with full bounds', () => {
2020-03-20 20:28:31 +00:00
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getBounds(), fullBounds);
});
it('sets the window bounds with partial bounds', () => {
2020-03-20 20:28:31 +00:00
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
2020-03-20 20:28:31 +00:00
const boundsUpdate = { width: 200 };
w.setBounds(boundsUpdate as any);
2020-03-20 20:28:31 +00:00
const expectedBounds = Object.assign(fullBounds, boundsUpdate);
expectBoundsEqual(w.getBounds(), expectedBounds);
});
});
describe('BrowserWindow.setSize(width, height)', () => {
it('sets the window size', async () => {
2020-03-20 20:28:31 +00:00
const size = [300, 400];
2020-03-20 20:28:31 +00:00
const resized = emittedOnce(w, 'resize');
w.setSize(size[0], size[1]);
await resized;
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getSize(), size);
});
});
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
it('sets the maximum and minimum size of the window', () => {
2020-03-20 20:28:31 +00:00
expect(w.getMinimumSize()).to.deep.equal([0, 0]);
expect(w.getMaximumSize()).to.deep.equal([0, 0]);
2020-03-20 20:28:31 +00:00
w.setMinimumSize(100, 100);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [0, 0]);
2020-03-20 20:28:31 +00:00
w.setMaximumSize(900, 600);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [900, 600]);
});
});
describe('BrowserWindow.setAspectRatio(ratio)', () => {
it('resets the behaviour when passing in 0', (done) => {
2020-03-20 20:28:31 +00:00
const size = [300, 400];
w.setAspectRatio(1 / 2);
w.setAspectRatio(0);
w.once('resize', () => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getSize(), size);
done();
});
w.setSize(size[0], size[1]);
});
});
describe('BrowserWindow.setPosition(x, y)', () => {
it('sets the window position', (done) => {
2020-03-20 20:28:31 +00:00
const pos = [10, 10];
w.once('move', () => {
2020-03-20 20:28:31 +00:00
const newPos = w.getPosition();
expect(newPos).to.deep.equal(pos);
done();
});
w.setPosition(pos[0], pos[1]);
});
});
describe('BrowserWindow.setContentSize(width, height)', () => {
it('sets the content size', (done) => {
// NB. The CI server has a very small screen. Attempting to size the window
// larger than the screen will limit the window's size to the screen and
// cause the test to fail.
2020-03-20 20:28:31 +00:00
const size = [456, 567];
w.setContentSize(size[0], size[1]);
setImmediate(() => {
2020-03-20 20:28:31 +00:00
const after = w.getContentSize();
expect(after).to.deep.equal(size);
done();
});
});
it('works for a frameless window', (done) => {
2020-03-20 20:28:31 +00:00
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
2020-03-20 20:28:31 +00:00
});
const size = [456, 567];
w.setContentSize(size[0], size[1]);
setImmediate(() => {
2020-03-20 20:28:31 +00:00
const after = w.getContentSize();
expect(after).to.deep.equal(size);
done();
});
});
});
describe('BrowserWindow.setContentBounds(bounds)', () => {
it('sets the content size and position', (done) => {
2020-03-20 20:28:31 +00:00
const bounds = { x: 10, y: 10, width: 250, height: 250 };
w.once('resize', () => {
setTimeout(() => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getContentBounds(), bounds);
done();
});
});
w.setContentBounds(bounds);
});
it('works for a frameless window', (done) => {
2020-03-20 20:28:31 +00:00
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
2020-03-20 20:28:31 +00:00
});
const bounds = { x: 10, y: 10, width: 250, height: 250 };
w.once('resize', () => {
setTimeout(() => {
2020-03-20 20:28:31 +00:00
expect(w.getContentBounds()).to.deep.equal(bounds);
done();
});
});
w.setContentBounds(bounds);
});
});
describe('BrowserWindow.getBackgroundColor()', () => {
it('returns default value if no backgroundColor is set', () => {
2020-03-20 20:28:31 +00:00
w.destroy();
w = new BrowserWindow({});
expect(w.getBackgroundColor()).to.equal('#FFFFFF');
});
it('returns correct value if backgroundColor is set', () => {
2020-03-20 20:28:31 +00:00
const backgroundColor = '#BBAAFF';
w.destroy();
w = new BrowserWindow({
backgroundColor: backgroundColor
2020-03-20 20:28:31 +00:00
});
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct value from setBackgroundColor()', () => {
2020-03-20 20:28:31 +00:00
const backgroundColor = '#AABBFF';
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor(backgroundColor);
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
});
describe('BrowserWindow.getNormalBounds()', () => {
describe('Normal state', () => {
it('checks normal bounds after resize', (done) => {
2020-03-20 20:28:31 +00:00
const size = [300, 400];
w.once('resize', () => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
done();
});
w.setSize(size[0], size[1]);
});
it('checks normal bounds after move', (done) => {
2020-03-20 20:28:31 +00:00
const pos = [10, 10];
w.once('move', () => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
done();
});
w.setPosition(pos[0], pos[1]);
});
});
ifdescribe(process.platform !== 'linux')('Maximized state', () => {
it('checks normal bounds when maximized', (done) => {
2020-03-20 20:28:31 +00:00
const bounds = w.getBounds();
w.once('maximize', () => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getNormalBounds(), bounds);
done();
});
w.show();
w.maximize();
});
it('checks normal bounds when unmaximized', (done) => {
2020-03-20 20:28:31 +00:00
const bounds = w.getBounds();
w.once('maximize', () => {
2020-03-20 20:28:31 +00:00
w.unmaximize();
});
w.once('unmaximize', () => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getNormalBounds(), bounds);
done();
});
w.show();
w.maximize();
});
});
ifdescribe(process.platform !== 'linux')('Minimized state', () => {
it('checks normal bounds when minimized', (done) => {
2020-03-20 20:28:31 +00:00
const bounds = w.getBounds();
w.once('minimize', () => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getNormalBounds(), bounds);
done();
});
w.show();
w.minimize();
});
it('checks normal bounds when restored', (done) => {
2020-03-20 20:28:31 +00:00
const bounds = w.getBounds();
w.once('minimize', () => {
2020-03-20 20:28:31 +00:00
w.restore();
});
w.once('restore', () => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getNormalBounds(), bounds);
done();
});
w.show();
w.minimize();
});
});
ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
it('checks normal bounds when fullscreen\'ed', (done) => {
2020-03-20 20:28:31 +00:00
const bounds = w.getBounds();
w.once('enter-full-screen', () => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getNormalBounds(), bounds);
done();
});
w.show();
w.setFullScreen(true);
});
it('checks normal bounds when unfullscreen\'ed', (done) => {
2020-03-20 20:28:31 +00:00
const bounds = w.getBounds();
w.once('enter-full-screen', () => {
2020-03-20 20:28:31 +00:00
w.setFullScreen(false);
});
w.once('leave-full-screen', () => {
2020-03-20 20:28:31 +00:00
expectBoundsEqual(w.getNormalBounds(), bounds);
done();
});
w.show();
w.setFullScreen(true);
});
});
});
});
ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.selectPreviousTab()', () => {
it('does not throw', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.selectPreviousTab();
}).to.not.throw();
});
});
describe('BrowserWindow.selectNextTab()', () => {
it('does not throw', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.selectNextTab();
}).to.not.throw();
});
});
describe('BrowserWindow.mergeAllWindows()', () => {
it('does not throw', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.mergeAllWindows();
}).to.not.throw();
});
});
describe('BrowserWindow.moveTabToNewWindow()', () => {
it('does not throw', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.moveTabToNewWindow();
}).to.not.throw();
});
});
describe('BrowserWindow.toggleTabBar()', () => {
it('does not throw', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.toggleTabBar();
}).to.not.throw();
});
});
describe('BrowserWindow.addTabbedWindow()', () => {
it('does not throw', async () => {
2020-03-20 20:28:31 +00:00
const tabbedWindow = new BrowserWindow({});
expect(() => {
2020-03-20 20:28:31 +00:00
w.addTabbedWindow(tabbedWindow);
}).to.not.throw();
2020-03-20 20:28:31 +00:00
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
2020-03-20 20:28:31 +00:00
await closeWindow(tabbedWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
});
it('throws when called on itself', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.addTabbedWindow(w);
}).to.throw('AddTabbedWindow cannot be called by a window on itself.');
});
});
});
describe('autoHideMenuBar state', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('for properties', () => {
it('can be set with autoHideMenuBar constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
w.autoHideMenuBar = true;
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
w.autoHideMenuBar = false;
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
});
});
it('for functions', () => {
it('can be set with autoHideMenuBar constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
w.setAutoHideMenuBar(true);
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
w.setAutoHideMenuBar(false);
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
});
});
});
describe('BrowserWindow.capturePage(rect)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('returns a Promise with a Buffer', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const image = await w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
expect(image.isEmpty()).to.equal(true);
});
it('preserves transparency', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, transparent: true });
w.loadURL('about:blank');
await emittedOnce(w, 'ready-to-show');
w.show();
2020-03-20 20:28:31 +00:00
const image = await w.capturePage();
const imgBuffer = image.toPNG();
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
2020-03-20 20:28:31 +00:00
expect(imgBuffer[25]).to.equal(6);
});
});
describe('BrowserWindow.setProgressBar(progress)', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
before(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false });
});
after(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('sets the progress', () => {
expect(() => {
if (process.platform === 'darwin') {
2020-03-20 20:28:31 +00:00
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
}
2020-03-20 20:28:31 +00:00
w.setProgressBar(0.5);
if (process.platform === 'darwin') {
2020-03-20 20:28:31 +00:00
app.dock.setIcon(null as any);
}
2020-03-20 20:28:31 +00:00
w.setProgressBar(-1);
}).to.not.throw();
});
it('sets the progress using "paused" mode', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.setProgressBar(0.5, { mode: 'paused' });
}).to.not.throw();
});
it('sets the progress using "error" mode', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.setProgressBar(0.5, { mode: 'error' });
}).to.not.throw();
});
it('sets the progress using "normal" mode', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.setProgressBar(0.5, { mode: 'normal' });
}).to.not.throw();
});
});
describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('sets the window as always on top', () => {
2020-03-20 20:28:31 +00:00
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
w.setAlwaysOnTop(false);
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('resets the windows level on minimize', () => {
2020-03-20 20:28:31 +00:00
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
w.minimize();
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.restore();
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
it('causes the right value to be emitted on `always-on-top-changed`', (done) => {
w.on('always-on-top-changed', (e, alwaysOnTop) => {
2020-03-20 20:28:31 +00:00
expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
done();
});
2020-03-20 20:28:31 +00:00
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
});
});
describe('preconnect feature', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
2020-03-20 20:28:31 +00:00
let server = null as unknown as http.Server;
let url = null as unknown as string;
let connections = 0;
beforeEach(async () => {
2020-03-20 20:28:31 +00:00
connections = 0;
server = http.createServer((req, res) => {
if (req.url === '/link') {
2020-03-20 20:28:31 +00:00
res.setHeader('Content-type', 'text/html');
res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
return;
}
2020-03-20 20:28:31 +00:00
res.end();
});
server.on('connection', () => { connections++; });
2020-03-20 20:28:31 +00:00
await new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve()));
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
server.close();
await closeWindow(w);
w = null as unknown as BrowserWindow;
server = null as unknown as http.Server;
});
it('calling preconnect() connects to the server', (done) => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false });
2019-11-01 20:37:02 +00:00
w.webContents.on('did-start-navigation', (event, url) => {
2020-03-20 20:28:31 +00:00
w.webContents.session.preconnect({ url, numSockets: 4 });
});
w.webContents.on('did-finish-load', () => {
2020-03-20 20:28:31 +00:00
expect(connections).to.equal(4);
done();
});
w.loadURL(url);
});
it('does not preconnect unless requested', async () => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false });
await w.loadURL(url);
expect(connections).to.equal(1);
});
it('parses <link rel=preconnect>', async () => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: true });
const p = emittedOnce(w.webContents.session, 'preconnect');
w.loadURL(url + '/link');
const [, preconnectUrl, allowCredentials] = await p;
expect(preconnectUrl).to.equal('http://example.com/');
expect(allowCredentials).to.be.true('allowCredentials');
});
});
describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
2020-03-20 20:28:31 +00:00
let w = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('allows changing cursor auto-hiding', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
w.setAutoHideCursor(false);
w.setAutoHideCursor(true);
}).to.not.throw();
});
});
ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
it('is not available', () => {
2020-03-20 20:28:31 +00:00
expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
});
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('does not throw', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(() => {
2020-03-20 20:28:31 +00:00
w.setWindowButtonVisibility(true);
w.setWindowButtonVisibility(false);
}).to.not.throw();
});
it('throws with custom title bar buttons', () => {
expect(() => {
const w = new BrowserWindow({
show: false,
titleBarStyle: 'customButtonsOnHover',
frame: false
2020-03-20 20:28:31 +00:00
});
w.setWindowButtonVisibility(true);
}).to.throw('Not supported for this window');
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('allows setting, changing, and removing the vibrancy', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(() => {
2020-03-20 20:28:31 +00:00
w.setVibrancy('light');
w.setVibrancy('dark');
w.setVibrancy(null);
w.setVibrancy('ultra-dark');
w.setVibrancy('' as any);
}).to.not.throw();
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.getTrafficLightPosition(pos)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('gets the set traffic light position property', () => {
2020-03-20 20:28:31 +00:00
const pos = { x: 10, y: 10 };
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const currentPosition = w.getTrafficLightPosition();
2020-03-20 20:28:31 +00:00
expect(currentPosition).to.deep.equal(pos);
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setTrafficLightPosition(pos)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('can set the traffic light position property', () => {
2020-03-20 20:28:31 +00:00
const pos = { x: 10, y: 10 };
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setTrafficLightPosition(pos);
const currentPosition = w.getTrafficLightPosition();
2020-03-20 20:28:31 +00:00
expect(currentPosition).to.deep.equal(pos);
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('supports setting the app details', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const iconPath = path.join(fixtures, 'assets', 'icon.ico');
expect(() => {
2020-03-20 20:28:31 +00:00
w.setAppDetails({ appId: 'my.app.id' });
w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
w.setAppDetails({ appIconPath: iconPath });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
w.setAppDetails({ relaunchDisplayName: 'My app name' });
w.setAppDetails({
appId: 'my.app.id',
appIconPath: iconPath,
appIconIndex: 0,
relaunchCommand: 'my-app.exe arg1 arg2',
relaunchDisplayName: 'My app name'
2020-03-20 20:28:31 +00:00
});
w.setAppDetails({});
}).to.not.throw();
expect(() => {
2020-03-20 20:28:31 +00:00
(w.setAppDetails as any)();
}).to.throw('Insufficient number of arguments.');
});
});
describe('BrowserWindow.fromId(id)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('returns the window with id', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(BrowserWindow.fromId(w.id).id).to.equal(w.id);
});
});
describe('BrowserWindow.fromWebContents(webContents)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('returns the window with the webContents', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const found = BrowserWindow.fromWebContents(w.webContents);
expect(found!.id).to.equal(w.id);
});
it('returns null for webContents without a BrowserWindow', () => {
2020-03-20 20:28:31 +00:00
const contents = (webContents as any).create({});
try {
2020-03-20 20:28:31 +00:00
expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
} finally {
2020-03-20 20:28:31 +00:00
contents.destroy();
}
2020-03-20 20:28:31 +00:00
});
});
describe('BrowserWindow.openDevTools()', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('does not crash for frameless window', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, frame: false });
w.webContents.openDevTools();
});
});
describe('BrowserWindow.fromBrowserView(browserView)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('returns the window with the browserView', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
// if BrowserView isn't explicitly destroyed, it will crash in GC later
2020-03-20 20:28:31 +00:00
bv.destroy();
});
it('returns undefined if not attached', () => {
2020-03-20 20:28:31 +00:00
const bv = new BrowserView();
expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
// if BrowserView isn't explicitly destroyed, it will crash in GC later
2020-03-20 20:28:31 +00:00
bv.destroy();
});
});
describe('BrowserWindow.setOpacity(opacity)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
it('make window with initial opacity', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, opacity: 0.5 });
expect(w.getOpacity()).to.equal(0.5);
});
it('allows setting the opacity', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(() => {
2020-03-20 20:28:31 +00:00
w.setOpacity(0.0);
expect(w.getOpacity()).to.equal(0.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(0.5);
w.setOpacity(1.0);
expect(w.getOpacity()).to.equal(1.0);
}).to.not.throw();
});
it('clamps opacity to [0.0...1.0]', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, opacity: 0.5 });
w.setOpacity(100);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(-100);
expect(w.getOpacity()).to.equal(0.0);
});
});
ifdescribe(process.platform === 'linux')(('Linux'), () => {
it('sets 1 regardless of parameter', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.setOpacity(0);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(1.0);
});
});
});
describe('BrowserWindow.setShape(rects)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('allows setting shape', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(() => {
2020-03-20 20:28:31 +00:00
w.setShape([]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
w.setShape([]);
}).to.not.throw();
});
});
describe('"useContentSize" option', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('make window created with content size when used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
2020-03-20 20:28:31 +00:00
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('make window created with window size when not used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
2019-11-01 20:37:02 +00:00
height: 400
2020-03-20 20:28:31 +00:00
});
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
it('works for a frameless window', () => {
const w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
2020-03-20 20:28:31 +00:00
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
});
ifdescribe(process.platform === 'darwin' && parseInt(os.release().split('.')[0]) >= 14)('"titleBarStyle" option', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('creates browser window with hidden title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
2020-03-20 20:28:31 +00:00
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('creates browser window with hidden inset title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hiddenInset'
2020-03-20 20:28:31 +00:00
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
});
ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('can move the window out of screen', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after).to.deep.equal([-10, -10]);
});
it('without it, cannot move the window out of screen', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can set the window larger than screen', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expectBoundsEqual(w.getSize(), [size.width, size.height]);
});
it('without it, cannot set the window larger than screen', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
});
});
ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('sets the window width to the page width when used', () => {
const w = new BrowserWindow({
show: false,
width: 500,
height: 400,
zoomToPageWidth: true
2020-03-20 20:28:31 +00:00
});
w.maximize();
expect(w.getSize()[0]).to.equal(500);
});
});
describe('"tabbingIdentifier" option', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('can be set on a window', () => {
expect(() => {
2019-11-01 20:37:02 +00:00
/* eslint-disable no-new */
new BrowserWindow({
tabbingIdentifier: 'group1'
2020-03-20 20:28:31 +00:00
});
new BrowserWindow({
tabbingIdentifier: 'group2',
frame: false
2020-03-20 20:28:31 +00:00
});
2019-11-01 20:37:02 +00:00
/* eslint-enable no-new */
2020-03-20 20:28:31 +00:00
}).not.to.throw();
});
});
describe('"webPreferences" option', () => {
2020-03-20 20:28:31 +00:00
afterEach(() => { ipcMain.removeAllListeners('answer'); });
afterEach(closeAllWindows);
describe('"preload" option', () => {
const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
it(name, async () => {
const w = new BrowserWindow({
webPreferences: {
...webPrefs,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
const [, result] = await emittedOnce(ipcMain, 'leak-result');
expect(result).to.have.property('require', 'undefined');
expect(result).to.have.property('exports', 'undefined');
expect(result).to.have.property('windowExports', 'undefined');
expect(result).to.have.property('windowPreload', 'undefined');
expect(result).to.have.property('windowRequire', 'undefined');
});
};
doesNotLeakSpec('does not leak require', {
nodeIntegration: false,
sandbox: false,
contextIsolation: false
2020-03-20 20:28:31 +00:00
});
doesNotLeakSpec('does not leak require when sandbox is enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: false
2020-03-20 20:28:31 +00:00
});
doesNotLeakSpec('does not leak require when context isolation is enabled', {
nodeIntegration: false,
sandbox: false,
contextIsolation: true
2020-03-20 20:28:31 +00:00
});
doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: true
2020-03-20 20:28:31 +00:00
});
it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
let w = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result');
expect(notIsolated).to.have.property('globals');
2020-03-20 20:28:31 +00:00
w.destroy();
w = new BrowserWindow({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, isolated] = await emittedOnce(ipcMain, 'leak-result');
expect(isolated).to.have.property('globals');
const notIsolatedGlobals = new Set(notIsolated.globals);
for (const isolatedGlobal of isolated.globals) {
2020-03-20 20:28:31 +00:00
notIsolatedGlobals.delete(isolatedGlobal);
}
2020-03-20 20:28:31 +00:00
expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals');
});
it('loads the script before other scripts in window', async () => {
2020-03-20 20:28:31 +00:00
const preload = path.join(fixtures, 'module', 'set-global.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await emittedOnce(ipcMain, 'answer');
expect(test).to.eql('preload');
});
it('can successfully delete the Buffer global', async () => {
2020-03-20 20:28:31 +00:00
const preload = path.join(__dirname, 'fixtures', 'module', 'delete-buffer.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
preload
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await emittedOnce(ipcMain, 'answer');
expect(test).to.eql(Buffer.from('buffer'));
});
it('has synchronous access to all eventual window APIs', async () => {
2020-03-20 20:28:31 +00:00
const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await emittedOnce(ipcMain, 'answer');
expect(test).to.be.an('object');
expect(test.atPreload).to.be.an('array');
expect(test.atLoad).to.be.an('array');
expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
});
});
describe('session preload scripts', function () {
const preloads = [
path.join(fixtures, 'module', 'set-global-preload-1.js'),
path.join(fixtures, 'module', 'set-global-preload-2.js'),
path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
2020-03-20 20:28:31 +00:00
];
const defaultSession = session.defaultSession;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
expect(defaultSession.getPreloads()).to.deep.equal([]);
defaultSession.setPreloads(preloads);
});
afterEach(() => {
2020-03-20 20:28:31 +00:00
defaultSession.setPreloads([]);
});
it('can set multiple session preload script', () => {
2020-03-20 20:28:31 +00:00
expect(defaultSession.getPreloads()).to.deep.equal(preloads);
});
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
refactor: use v8 serialization for ipc (#20214) * refactor: use v8 serialization for ipc * cloning process.env doesn't work * serialize host objects by enumerating key/values * new serialization can handle NaN, Infinity, and undefined correctly * can't allocate v8 objects during GC * backport microtasks fix * fix compile * fix node_stream_loader reentrancy * update subframe spec to expect undefined instead of null * write undefined instead of crashing when serializing host objects * fix webview spec * fix download spec * buffers are transformed into uint8arrays * can't serialize promises * fix chrome.i18n.getMessage * fix devtools tests * fix zoom test * fix debug build * fix lint * update ipcRenderer tests * fix printToPDF test * update patch * remove accidentally re-added remote-side spec * wip * don't attempt to serialize host objects * jump through different hoops to set options.webContents sometimes * whoops * fix lint * clean up error-handling logic * fix memory leak * fix lint * convert host objects using old base::Value serialization * fix lint more * fall back to base::Value-based serialization * remove commented-out code * add docs to breaking-changes.md * Update breaking-changes.md * update ipcRenderer and WebContents docs * lint * use named values for format tag * save a memcpy for ~30% speedup * get rid of calls to ShallowClone * extra debugging for paranoia * d'oh, use the correct named tags * apparently msstl doesn't like this DCHECK * funny story about that DCHECK * disable remote-related functions when enable_remote_module = false * nits * use EnableIf to disable remote methods in mojom * fix include * review comments
2019-10-09 17:59:08 +00:00
it('loads the script before other scripts in window including normal preloads', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload: path.join(fixtures, 'module', 'get-global-preload.js')
}
2020-03-20 20:28:31 +00:00
});
w.loadURL('about:blank');
const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars');
expect(preload1).to.equal('preload-1');
expect(preload2).to.equal('preload-1-2');
expect(preload3).to.be.undefined('preload 3');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('"additionalArguments" option', () => {
it('adds extra args to process.argv in the renderer process', async () => {
2020-03-20 20:28:31 +00:00
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg']
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await emittedOnce(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg');
});
it('adds extra value args to process.argv in the renderer process', async () => {
2020-03-20 20:28:31 +00:00
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg=foo']
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await emittedOnce(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg=foo');
});
});
describe('"node-integration" option', () => {
it('disables node integration by default', async () => {
2020-03-20 20:28:31 +00:00
const preload = path.join(fixtures, 'module', 'send-later.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
preload
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer');
expect(typeofProcess).to.equal('undefined');
expect(typeofBuffer).to.equal('undefined');
});
});
describe('"enableRemoteModule" option', () => {
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
2020-03-20 20:28:31 +00:00
const preload = path.join(__dirname, 'fixtures', 'module', 'preload-remote.js');
it('disables the remote module by default', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
sandbox
}
2020-03-20 20:28:31 +00:00
});
const p = emittedOnce(ipcMain, 'remote');
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, remote] = await p;
expect(remote).to.equal('undefined');
});
it('disables the remote module when false', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
sandbox,
enableRemoteModule: false
}
2020-03-20 20:28:31 +00:00
});
const p = emittedOnce(ipcMain, 'remote');
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, remote] = await p;
expect(remote).to.equal('undefined');
});
it('enables the remote module when true', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
sandbox,
enableRemoteModule: true
}
2020-03-20 20:28:31 +00:00
});
const p = emittedOnce(ipcMain, 'remote');
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, remote] = await p;
expect(remote).to.equal('object');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('"sandbox" option', () => {
function waitForEvents<T> (emitter: { once: Function }, events: string[], callback: () => void) {
2020-03-20 20:28:31 +00:00
let count = events.length;
for (const event of events) {
emitter.once(event, () => {
2020-03-20 20:28:31 +00:00
if (!--count) callback();
});
}
}
2020-03-20 20:28:31 +00:00
const preload = path.join(fixtures, 'module', 'preload-sandbox.js');
2020-03-20 20:28:31 +00:00
let server: http.Server = null as unknown as http.Server;
let serverUrl: string = null as unknown as string;
before((done) => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/cross-site':
2020-03-20 20:28:31 +00:00
response.end(`<html><body><h1>${request.url}</h1></body></html>`);
break;
default:
2020-03-20 20:28:31 +00:00
throw new Error(`unsupported endpoint: ${request.url}`);
}
}).listen(0, '127.0.0.1', () => {
2020-03-20 20:28:31 +00:00
serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
done();
});
});
after(() => {
2020-03-20 20:28:31 +00:00
server.close();
});
it('exposes ipcRenderer to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await emittedOnce(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes ipcRenderer to preload script (path has special chars)', async () => {
2020-03-20 20:28:31 +00:00
const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preloadSpecialChars
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await emittedOnce(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes "loaded" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
2020-03-20 20:28:31 +00:00
});
w.loadURL('about:blank');
await emittedOnce(ipcMain, 'process-loaded');
});
it('exposes "exit" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
2020-03-20 20:28:31 +00:00
});
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
const pageUrl = 'file://' + htmlPath;
w.loadURL(pageUrl);
const [, url] = await emittedOnce(ipcMain, 'answer');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
2020-03-20 20:28:31 +00:00
: pageUrl;
expect(url).to.equal(expectedUrl);
});
it('should open windows in same domain with cross-scripting enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = preload;
});
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
const pageUrl = 'file://' + htmlPath;
const answer = emittedOnce(ipcMain, 'answer');
w.loadURL(pageUrl);
const [, url, frameName, , options] = await emittedOnce(w.webContents, 'new-window');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
2020-03-20 20:28:31 +00:00
: pageUrl;
expect(url).to.equal(expectedUrl);
expect(frameName).to.equal('popup!');
expect(options.width).to.equal(500);
expect(options.height).to.equal(600);
const [, html] = await answer;
expect(html).to.equal('<h1>scripting from opener</h1>');
});
it('should open windows in another domain with cross-scripting disabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = preload;
});
w.loadFile(
path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
{ search: 'window-open-external' }
2020-03-20 20:28:31 +00:00
);
// Wait for a message from the main window saying that it's ready.
2020-03-20 20:28:31 +00:00
await emittedOnce(ipcMain, 'opener-loaded');
// Ask the opener to open a popup with window.opener.
2020-03-20 20:28:31 +00:00
const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
2020-03-20 20:28:31 +00:00
w.webContents.send('open-the-popup', expectedPopupUrl);
// The page is going to open a popup that it won't be able to close.
// We have to close it from here later.
2020-03-20 20:28:31 +00:00
const [, popupWindow] = await emittedOnce(app, 'browser-window-created');
// Ask the popup window for details.
2020-03-20 20:28:31 +00:00
const detailsAnswer = emittedOnce(ipcMain, 'child-loaded');
popupWindow.webContents.send('provide-details');
const [, openerIsNull, , locationHref] = await detailsAnswer;
expect(openerIsNull).to.be.false('window.opener is null');
expect(locationHref).to.equal(expectedPopupUrl);
// Ask the page to access the popup.
2020-03-20 20:28:31 +00:00
const touchPopupResult = emittedOnce(ipcMain, 'answer');
w.webContents.send('touch-the-popup');
const [, popupAccessMessage] = await touchPopupResult;
// Ask the popup to access the opener.
2020-03-20 20:28:31 +00:00
const touchOpenerResult = emittedOnce(ipcMain, 'answer');
popupWindow.webContents.send('touch-the-opener');
const [, openerAccessMessage] = await touchOpenerResult;
// We don't need the popup anymore, and its parent page can't close it,
// so let's close it from here before we run any checks.
2020-03-20 20:28:31 +00:00
await closeWindow(popupWindow, { assertNotWindows: false });
expect(popupAccessMessage).to.be.a('string',
2020-03-20 20:28:31 +00:00
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
expect(openerAccessMessage).to.be.a('string',
2020-03-20 20:28:31 +00:00
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
});
it('should inherit the sandbox setting in opened windows', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = preloadPath;
});
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [, args] = await emittedOnce(ipcMain, 'answer');
expect(args).to.include('--enable-sandbox');
});
it('should open windows with the options configured via new-window event listeners', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = preloadPath;
const prefs = options.webPreferences as any;
prefs.foo = 'bar';
});
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
emittedOnce(app, 'web-contents-created'),
emittedOnce(ipcMain, 'answer')
2020-03-20 20:28:31 +00:00
]);
const webPreferences = (childWebContents as any).getLastWebPreferences();
expect(webPreferences.foo).to.equal('bar');
});
it('should set ipc event sender correctly', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
2020-03-20 20:28:31 +00:00
});
let childWc: WebContents | null = null;
w.webContents.on('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = preload;
childWc = (options as any).webContents;
expect(w.webContents).to.not.equal(childWc);
});
ipcMain.once('parent-ready', function (event) {
2020-03-20 20:28:31 +00:00
expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
event.sender.send('verified');
});
ipcMain.once('child-ready', function (event) {
2020-03-20 20:28:31 +00:00
expect(childWc).to.not.be.null('child webcontents should be available');
expect(event.sender).to.equal(childWc, 'sender should be the child');
event.sender.send('verified');
});
waitForEvents(ipcMain, [
'parent-answer',
'child-answer'
2020-03-20 20:28:31 +00:00
], done);
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
});
describe('event handling', () => {
2020-03-20 20:28:31 +00:00
let w: BrowserWindow = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
});
it('works for window events', (done) => {
waitForEvents(w, [
'page-title-updated'
2020-03-20 20:28:31 +00:00
], done);
w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
});
it('works for stop events', (done) => {
waitForEvents(w.webContents, [
'did-navigate',
'did-fail-load',
'did-stop-loading'
2020-03-20 20:28:31 +00:00
], done);
w.loadURL('data:text/html,<script>stop()</script>');
});
it('works for web contents events', (done) => {
waitForEvents(w.webContents, [
'did-finish-load',
'did-frame-finish-load',
'did-navigate-in-page',
'will-navigate',
'did-start-loading',
'did-stop-loading',
'did-frame-finish-load',
'dom-ready'
2020-03-20 20:28:31 +00:00
], done);
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
});
});
it('supports calling preventDefault on new-window events', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
2020-03-20 20:28:31 +00:00
});
const initialWebContents = webContents.getAllWebContents().map((i) => i.id);
w.webContents.once('new-window', (e) => {
2020-03-20 20:28:31 +00:00
e.preventDefault();
// We need to give it some time so the windows get properly disposed (at least on OSX).
setTimeout(() => {
2020-03-20 20:28:31 +00:00
const currentWebContents = webContents.getAllWebContents().map((i) => i.id);
expect(currentWebContents).to.deep.equal(initialWebContents);
done();
}, 100);
});
w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
});
// see #9387
it('properly manages remote object references after page reload', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
sandbox: true,
enableRemoteModule: true
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'reload-remote' });
ipcMain.on('get-remote-module-path', (event) => {
2020-03-20 20:28:31 +00:00
event.returnValue = path.join(fixtures, 'module', 'hello.js');
});
2020-03-20 20:28:31 +00:00
let reload = false;
ipcMain.on('reloaded', (event) => {
2020-03-20 20:28:31 +00:00
event.returnValue = reload;
reload = !reload;
});
ipcMain.once('reload', (event) => {
2020-03-20 20:28:31 +00:00
event.sender.reload();
});
ipcMain.once('answer', (event, arg) => {
2020-03-20 20:28:31 +00:00
ipcMain.removeAllListeners('reloaded');
ipcMain.removeAllListeners('get-remote-module-path');
expect(arg).to.equal('hi');
done();
});
});
it('properly manages remote object references after page reload in child window', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
sandbox: true,
enableRemoteModule: true
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = preload;
});
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'reload-remote-child' });
ipcMain.on('get-remote-module-path', (event) => {
2020-03-20 20:28:31 +00:00
event.returnValue = path.join(fixtures, 'module', 'hello-child.js');
});
2020-03-20 20:28:31 +00:00
let reload = false;
ipcMain.on('reloaded', (event) => {
2020-03-20 20:28:31 +00:00
event.returnValue = reload;
reload = !reload;
});
ipcMain.once('reload', (event) => {
2020-03-20 20:28:31 +00:00
event.sender.reload();
});
ipcMain.once('answer', (event, arg) => {
2020-03-20 20:28:31 +00:00
ipcMain.removeAllListeners('reloaded');
ipcMain.removeAllListeners('get-remote-module-path');
expect(arg).to.equal('hi child window');
done();
});
});
it('validates process APIs access in sandboxed renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('preload-error', (event, preloadPath, error) => {
2020-03-20 20:28:31 +00:00
throw error;
});
process.env.sandboxmain = 'foo';
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await emittedOnce(ipcMain, 'answer');
expect(test.hasCrash).to.be.true('has crash');
expect(test.hasHang).to.be.true('has hang');
expect(test.heapStatistics).to.be.an('object');
expect(test.blinkMemoryInfo).to.be.an('object');
expect(test.processMemoryInfo).to.be.an('object');
expect(test.systemVersion).to.be.a('string');
expect(test.cpuUsage).to.be.an('object');
expect(test.ioCounters).to.be.an('object');
expect(test.arch).to.equal(process.arch);
expect(test.platform).to.equal(process.platform);
expect(test.env).to.deep.equal(process.env);
expect(test.execPath).to.equal(process.helperExecPath);
expect(test.sandboxed).to.be.true('sandboxed');
expect(test.type).to.equal('renderer');
expect(test.version).to.equal(process.version);
expect(test.versions).to.deep.equal(process.versions);
if (process.platform === 'linux' && test.osSandbox) {
2020-03-20 20:28:31 +00:00
expect(test.creationTime).to.be.null('creation time');
expect(test.systemMemoryInfo).to.be.null('system memory info');
} else {
2020-03-20 20:28:31 +00:00
expect(test.creationTime).to.be.a('number');
expect(test.systemMemoryInfo).to.be.an('object');
}
2020-03-20 20:28:31 +00:00
});
it('webview in sandbox renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
webviewTag: true
}
2020-03-20 20:28:31 +00:00
});
const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview');
const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
2020-03-20 20:28:31 +00:00
const [, webContents] = await didAttachWebview;
const [, id] = await webviewDomReady;
expect(webContents.id).to.equal(id);
});
});
describe('nativeWindowOpen option', () => {
2020-03-20 20:28:31 +00:00
let w: BrowserWindow = null as unknown as BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nativeWindowOpen: true,
// tests relies on preloads in opened windows
nodeIntegrationInSubFrames: true
}
2020-03-20 20:28:31 +00:00
});
});
it('opens window of about:blank with cross-scripting enabled', (done) => {
ipcMain.once('answer', (event, content) => {
2020-03-20 20:28:31 +00:00
expect(content).to.equal('Hello');
done();
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
});
it('opens window of same domain with cross-scripting enabled', (done) => {
ipcMain.once('answer', (event, content) => {
2020-03-20 20:28:31 +00:00
expect(content).to.equal('Hello');
done();
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
});
it('blocks accessing cross-origin frames', (done) => {
ipcMain.once('answer', (event, content) => {
2020-03-20 20:28:31 +00:00
expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
done();
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
});
it('opens window from <iframe> tags', (done) => {
ipcMain.once('answer', (event, content) => {
2020-03-20 20:28:31 +00:00
expect(content).to.equal('Hello');
done();
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
{
2020-03-20 20:28:31 +00:00
const [, content] = await emittedOnce(ipcMain, 'answer');
expect(content).to.equal('function');
}
2020-03-20 20:28:31 +00:00
w.reload();
{
2020-03-20 20:28:31 +00:00
const [, content] = await emittedOnce(ipcMain, 'answer');
expect(content).to.equal('function');
}
2020-03-20 20:28:31 +00:00
});
it('<webview> works in a scriptable popup', (done) => {
2020-03-20 20:28:31 +00:00
const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegrationInSubFrames: true,
nativeWindowOpen: true,
webviewTag: true,
preload
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.show = false;
});
ipcMain.once('webview-loaded', () => {
2020-03-20 20:28:31 +00:00
done();
});
w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
});
it('should inherit the nativeWindowOpen setting in opened windows', async () => {
2020-03-20 20:28:31 +00:00
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = preloadPath;
});
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [, args] = await emittedOnce(ipcMain, 'answer');
expect(args).to.include('--native-window-open');
});
it('should open windows with the options configured via new-window event listeners', async () => {
2020-03-20 20:28:31 +00:00
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = preloadPath;
const prefs = options.webPreferences! as any;
prefs.foo = 'bar';
});
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
emittedOnce(app, 'web-contents-created'),
emittedOnce(ipcMain, 'answer')
2020-03-20 20:28:31 +00:00
]);
const webPreferences = (childWebContents as any).getLastWebPreferences();
expect(webPreferences.foo).to.equal('bar');
});
describe('window.location', () => {
const protocols = [
['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
2020-03-20 20:28:31 +00:00
];
beforeEach(async () => {
await Promise.all(protocols.map(([scheme, path]) => new Promise((resolve, reject) => {
protocol.registerBufferProtocol(scheme, (request, callback) => {
callback({
mimeType: 'text/html',
data: fs.readFileSync(path)
2020-03-20 20:28:31 +00:00
});
}, (error) => {
if (error != null) {
2020-03-20 20:28:31 +00:00
reject(error);
} else {
2020-03-20 20:28:31 +00:00
resolve();
}
2020-03-20 20:28:31 +00:00
});
})));
});
afterEach(async () => {
2019-11-01 20:37:02 +00:00
await Promise.all(protocols.map(([scheme]) => {
2020-03-20 20:28:31 +00:00
return new Promise(resolve => protocol.unregisterProtocol(scheme, () => resolve()));
}));
});
it('retains the original web preferences when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true,
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = path.join(fixtures, 'api', 'window-open-preload.js');
});
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, args, typeofProcess] = await emittedOnce(ipcMain, 'answer');
expect(args).not.to.include('--node-integration');
expect(args).to.include('--native-window-open');
expect(typeofProcess).to.eql('undefined');
});
it('window.opener is not null when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true,
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
2020-03-20 20:28:31 +00:00
options.webPreferences!.preload = path.join(fixtures, 'api', 'window-open-preload.js');
});
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, , , windowOpenerIsNull] = await emittedOnce(ipcMain, 'answer');
expect(windowOpenerIsNull).to.be.false('window.opener is null');
});
});
});
describe('"disableHtmlFullscreenWindowResize" option', () => {
it('prevents window from resizing when set', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
disableHtmlFullscreenWindowResize: true
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('did-finish-load', () => {
2020-03-20 20:28:31 +00:00
const size = w.getSize();
w.webContents.once('enter-html-full-screen', () => {
2020-03-20 20:28:31 +00:00
const newSize = w.getSize();
expect(newSize).to.deep.equal(size);
done();
});
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
});
w.loadURL('about:blank');
});
});
});
describe('nativeWindowOpen + contextIsolation options', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('opens window with cross-scripting enabled from isolated context', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
const [, content] = await emittedOnce(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
});
describe('beforeunload handler', function () {
// TODO(nornagon): I feel like these tests _oughtn't_ be flakey, but
// beforeunload is in general not reliable on the web, so i'm not going to
// worry about it too much for now.
2020-03-20 20:28:31 +00:00
this.retries(3);
2020-03-20 20:28:31 +00:00
let w: BrowserWindow = null as unknown as BrowserWindow;
beforeEach(() => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(() => {
2020-03-20 20:28:31 +00:00
ipcMain.removeAllListeners('onbeforeunload');
});
afterEach(closeAllWindows);
it('returning undefined would not prevent close', (done) => {
2020-03-20 20:28:31 +00:00
w.once('closed', () => { done(); });
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'close-beforeunload-undefined.html'));
});
it('returning false would prevent close', async () => {
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'close-beforeunload-false.html'));
const [e] = await emittedOnce(ipcMain, 'onbeforeunload');
e.returnValue = null;
});
it('returning empty string would prevent close', (done) => {
2020-03-20 20:28:31 +00:00
ipcMain.once('onbeforeunload', (e) => { e.returnValue = null; done(); });
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'close-beforeunload-empty-string.html'));
});
it('emits for each close attempt', (done) => {
2020-03-20 20:28:31 +00:00
let beforeUnloadCount = 0;
ipcMain.on('onbeforeunload', (e) => {
2020-03-20 20:28:31 +00:00
e.returnValue = null;
beforeUnloadCount += 1;
if (beforeUnloadCount < 3) {
2020-03-20 20:28:31 +00:00
w.close();
} else if (beforeUnloadCount === 3) {
2020-03-20 20:28:31 +00:00
done();
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('did-finish-load', () => { w.webContents.executeJavaScript('window.close()', true); });
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
});
it('emits for each reload attempt', (done) => {
2020-03-20 20:28:31 +00:00
let beforeUnloadCount = 0;
ipcMain.on('onbeforeunload', (e) => {
2020-03-20 20:28:31 +00:00
e.returnValue = null;
beforeUnloadCount += 1;
if (beforeUnloadCount < 3) {
2020-03-20 20:28:31 +00:00
w.reload();
} else if (beforeUnloadCount === 3) {
2020-03-20 20:28:31 +00:00
done();
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('did-finish-load', () => {
w.webContents.once('did-finish-load', () => {
2020-03-20 20:28:31 +00:00
expect.fail('Reload was not prevented');
});
w.reload();
});
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
});
it('emits for each navigation attempt', (done) => {
2020-03-20 20:28:31 +00:00
let beforeUnloadCount = 0;
ipcMain.on('onbeforeunload', (e) => {
2020-03-20 20:28:31 +00:00
e.returnValue = null;
beforeUnloadCount += 1;
if (beforeUnloadCount < 3) {
2020-03-20 20:28:31 +00:00
w.loadURL('about:blank');
} else if (beforeUnloadCount === 3) {
2020-03-20 20:28:31 +00:00
done();
}
2020-03-20 20:28:31 +00:00
});
w.webContents.once('did-finish-load', () => {
w.webContents.once('did-finish-load', () => {
2020-03-20 20:28:31 +00:00
expect.fail('Navigation was not prevented');
});
w.loadURL('about:blank');
});
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
});
});
describe('document.visibilityState/hidden', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('visibilityState is initially visible despite window being hidden', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
let readyToShow = false;
w.once('ready-to-show', () => {
2020-03-20 20:28:31 +00:00
readyToShow = true;
});
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
2020-03-20 20:28:31 +00:00
const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
2020-03-20 20:28:31 +00:00
expect(readyToShow).to.be.false('ready to show');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
2020-03-20 20:28:31 +00:00
const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
2020-03-20 20:28:31 +00:00
w.hide();
{
2020-03-20 20:28:31 +00:00
const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
2020-03-20 20:28:31 +00:00
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
2020-03-20 20:28:31 +00:00
await emittedOnce(w, 'show');
}
2020-03-20 20:28:31 +00:00
w.hide();
w.show();
const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
2019-10-30 23:38:21 +00:00
ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
2020-03-20 20:28:31 +00:00
await emittedOnce(w, 'show');
}
2020-03-20 20:28:31 +00:00
w.hide();
w.showInactive();
const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
2020-03-20 20:28:31 +00:00
const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
2020-03-20 20:28:31 +00:00
w.minimize();
{
2020-03-20 20:28:31 +00:00
const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
2020-03-20 20:28:31 +00:00
});
// FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
// when we introduced the compositor recycling patch. Should figure out how to fix this
it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
nodeIntegration: true
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
2020-03-20 20:28:31 +00:00
const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
ipcMain.once('pong', (event, visibilityState, hidden) => {
2020-03-20 20:28:31 +00:00
throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
});
try {
2020-03-20 20:28:31 +00:00
const shown1 = emittedOnce(w, 'show');
w.show();
await shown1;
const hidden = emittedOnce(w, 'hide');
w.hide();
await hidden;
const shown2 = emittedOnce(w, 'show');
w.show();
await shown2;
} finally {
2020-03-20 20:28:31 +00:00
ipcMain.removeAllListeners('pong');
}
2020-03-20 20:28:31 +00:00
});
});
describe('new-window event', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('emits when window.open is called', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures) => {
2020-03-20 20:28:31 +00:00
e.preventDefault();
expect(url).to.equal('http://host/');
expect(frameName).to.equal('host');
expect(additionalFeatures[0]).to.equal('this-is-not-a-standard-feature');
done();
});
w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
});
it('emits when window.open is called with no webPreferences', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.once('new-window', function (e, url, frameName, disposition, options, additionalFeatures) {
2020-03-20 20:28:31 +00:00
e.preventDefault();
expect(url).to.equal('http://host/');
expect(frameName).to.equal('host');
expect(additionalFeatures[0]).to.equal('this-is-not-a-standard-feature');
done();
});
w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
});
it('emits when link with target is called', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.webContents.once('new-window', (e, url, frameName) => {
2020-03-20 20:28:31 +00:00
e.preventDefault();
expect(url).to.equal('http://host/');
expect(frameName).to.equal('target');
done();
});
w.loadFile(path.join(fixtures, 'pages', 'target-name.html'));
});
});
ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('emits an event when window is maximized', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.once('maximize', () => { done(); });
w.show();
w.maximize();
});
it('emits an event when window is unmaximized', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.once('unmaximize', () => { done(); });
w.show();
w.maximize();
w.unmaximize();
});
it('emits an event when window is minimized', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.once('minimize', () => { done(); });
w.show();
w.minimize();
});
});
describe('beginFrameSubscription method', () => {
it('does not crash when callback returns nothing', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
2019-11-01 20:37:02 +00:00
w.webContents.beginFrameSubscription(function () {
// Pending endFrameSubscription to next tick can reliably reproduce
// a crash which happens when nothing is returned in the callback.
setTimeout(() => {
2020-03-20 20:28:31 +00:00
w.webContents.endFrameSubscription();
done();
});
});
});
});
it('subscribes to frame updates', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function (data) {
// This callback might be called twice.
2020-03-20 20:28:31 +00:00
if (called) return;
called = true;
2020-03-20 20:28:31 +00:00
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
2020-03-20 20:28:31 +00:00
w.webContents.endFrameSubscription();
done();
});
});
});
it('subscribes to frame updates (only dirty rectangle)', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
let called = false;
let gotInitialFullSizeFrame = false;
const [contentWidth, contentHeight] = w.getContentSize();
w.webContents.on('did-finish-load', () => {
w.webContents.beginFrameSubscription(true, (image, rect) => {
if (image.isEmpty()) {
// Chromium sometimes sends a 0x0 frame at the beginning of the
// page load.
2020-03-20 20:28:31 +00:00
return;
}
if (rect.height === contentHeight && rect.width === contentWidth &&
!gotInitialFullSizeFrame) {
// The initial frame is full-size, but we're looking for a call
// with just the dirty-rect. The next frame should be a smaller
// rect.
2020-03-20 20:28:31 +00:00
gotInitialFullSizeFrame = true;
return;
}
// This callback might be called twice.
2020-03-20 20:28:31 +00:00
if (called) return;
// We asked for just the dirty rectangle, so we expect to receive a
// rect smaller than the full size.
// TODO(jeremy): this is failing on windows currently; investigate.
// assert(rect.width < contentWidth || rect.height < contentHeight)
2020-03-20 20:28:31 +00:00
called = true;
2020-03-20 20:28:31 +00:00
const expectedSize = rect.width * rect.height * 4;
expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
w.webContents.endFrameSubscription();
done();
});
});
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
});
it('throws error when subscriber is not well defined', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(() => {
2020-03-20 20:28:31 +00:00
w.webContents.beginFrameSubscription(true, true as any);
// TODO(zcbenz): gin is weak at guessing parameter types, we should
// upstream native_mate's implementation to gin.
2020-03-20 20:28:31 +00:00
}).to.throw('Error processing argument at index 1, conversion failure from ');
});
});
describe('savePage method', () => {
2020-03-20 20:28:31 +00:00
const savePageDir = path.join(fixtures, 'save_page');
const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
after(() => {
try {
2020-03-20 20:28:31 +00:00
fs.unlinkSync(savePageCssPath);
fs.unlinkSync(savePageJsPath);
fs.unlinkSync(savePageHtmlPath);
fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
fs.rmdirSync(savePageDir);
} catch (e) {
// Ignore error
}
2020-03-20 20:28:31 +00:00
});
afterEach(closeAllWindows);
it('should save page to disk', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
2020-03-20 20:28:31 +00:00
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
});
});
describe('BrowserWindow options argument is optional', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('should create a window with default size (800x600)', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow();
expect(w.getSize()).to.deep.equal([800, 600]);
});
});
describe('BrowserWindow.restore()', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('should restore the previous window size', () => {
const w = new BrowserWindow({
minWidth: 800,
width: 800
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const initialSize = w.getSize();
w.minimize();
w.restore();
expectBoundsEqual(w.getSize(), initialSize);
});
it('does not crash when restoring hidden minimized window', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({});
w.minimize();
w.hide();
w.show();
});
});
describe('BrowserWindow.unmaximize()', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('should restore the previous window position', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow();
2020-03-20 20:28:31 +00:00
const initialPosition = w.getPosition();
w.maximize();
w.unmaximize();
expectBoundsEqual(w.getPosition(), initialPosition);
});
});
describe('setFullScreen(false)', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
// only applicable to windows: https://github.com/electron/electron/issues/6036
ifdescribe(process.platform === 'win32')('on windows', () => {
it('should restore a normal visible window from a fullscreen startup state', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const shown = emittedOnce(w, 'show');
// start fullscreen and hidden
2020-03-20 20:28:31 +00:00
w.setFullScreen(true);
w.show();
await shown;
const leftFullScreen = emittedOnce(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.true('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
it('should keep window hidden if already in hidden state', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const leftFullScreen = emittedOnce(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.false('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
it('exits HTML fullscreen when window leaves fullscreen', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow();
await w.loadURL('about:blank');
await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await emittedOnce(w, 'enter-full-screen');
// Wait a tick for the full-screen state to 'stick'
2020-03-20 20:28:31 +00:00
await new Promise(resolve => setTimeout(resolve));
w.setFullScreen(false);
await emittedOnce(w, 'leave-html-full-screen');
});
});
});
describe('parent window', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow();
w.once('sheet-begin', () => {
2020-03-20 20:28:31 +00:00
done();
});
2019-11-01 20:37:02 +00:00
// eslint-disable-next-line no-new
new BrowserWindow({
modal: true,
parent: w
2020-03-20 20:28:31 +00:00
});
});
ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow();
const sheet = new BrowserWindow({
modal: true,
parent: w
2020-03-20 20:28:31 +00:00
});
w.once('sheet-end', () => { done(); });
sheet.close();
});
describe('parent option', () => {
it('sets parent window', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.getParentWindow()).to.equal(w);
});
it('adds window to child windows of parent', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(w.getChildWindows()).to.deep.equal([c]);
});
it('removes from child windows of parent when window is closed', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
c.once('closed', () => {
// The child window list is not immediately cleared, so wait a tick until it's ready.
setTimeout(() => {
2020-03-20 20:28:31 +00:00
expect(w.getChildWindows().length).to.equal(0);
done();
});
});
c.close();
});
it('should not affect the show option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.isVisible()).to.be.false('child is visible');
expect(c.getParentWindow().isVisible()).to.be.false('parent is visible');
});
});
describe('win.setParentWindow(parent)', () => {
it('sets parent window', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getParentWindow()).to.be.null('w.parent');
expect(c.getParentWindow()).to.be.null('c.parent');
c.setParentWindow(w);
expect(c.getParentWindow()).to.equal(w);
c.setParentWindow(null);
expect(c.getParentWindow()).to.be.null('c.parent');
});
it('adds window to child windows of parent', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getChildWindows()).to.deep.equal([]);
c.setParentWindow(w);
expect(w.getChildWindows()).to.deep.equal([c]);
c.setParentWindow(null);
expect(w.getChildWindows()).to.deep.equal([]);
});
it('removes from child windows of parent when window is closed', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
c.once('closed', () => {
// The child window list is not immediately cleared, so wait a tick until it's ready.
setTimeout(() => {
2020-03-20 20:28:31 +00:00
expect(w.getChildWindows().length).to.equal(0);
done();
});
});
c.setParentWindow(w);
c.close();
});
});
describe('modal option', () => {
it('does not freeze or crash', async () => {
2020-03-20 20:28:31 +00:00
const parentWindow = new BrowserWindow();
const createTwo = async () => {
const two = new BrowserWindow({
width: 300,
height: 200,
parent: parentWindow,
modal: true,
show: false
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const twoShown = emittedOnce(two, 'show');
two.show();
await twoShown;
setTimeout(() => two.close(), 500);
2020-03-20 20:28:31 +00:00
await emittedOnce(two, 'closed');
};
const one = new BrowserWindow({
width: 600,
height: 400,
parent: parentWindow,
modal: true,
show: false
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const oneShown = emittedOnce(one, 'show');
one.show();
await oneShown;
setTimeout(() => one.destroy(), 500);
2020-03-20 20:28:31 +00:00
await emittedOnce(one, 'closed');
await createTwo();
});
ifit(process.platform !== 'darwin')('disables parent window', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
expect(w.isEnabled()).to.be.true('w.isEnabled');
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
c.once('closed', () => {
2020-03-20 20:28:31 +00:00
expect(w.isEnabled()).to.be.true('w.isEnabled');
done();
});
c.show();
c.close();
});
ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
c.once('closed', () => {
2020-03-20 20:28:31 +00:00
expect(w.isEnabled()).to.be.false('w.isEnabled');
done();
});
w.setEnabled(false);
c.show();
c.close();
});
ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c.destroy();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.destroy();
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
});
});
describe('window states', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('does not resize frameless windows when states change', () => {
const w = new BrowserWindow({
frame: false,
width: 300,
height: 200,
show: false
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
w.minimizable = false;
w.minimizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
2020-03-20 20:28:31 +00:00
w.resizable = false;
w.resizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
2020-03-20 20:28:31 +00:00
w.maximizable = false;
w.maximizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
2020-03-20 20:28:31 +00:00
w.fullScreenable = false;
w.fullScreenable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
2020-03-20 20:28:31 +00:00
w.closable = false;
w.closable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
});
describe('resizable state', () => {
it('with properties', () => {
it('can be set with resizable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.resizable).to.be.false('resizable');
if (process.platform === 'darwin') {
2020-03-20 20:28:31 +00:00
expect(w.maximizable).to.to.true('maximizable');
}
2020-03-20 20:28:31 +00:00
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
w.resizable = false;
expect(w.resizable).to.be.false('resizable');
w.resizable = true;
expect(w.resizable).to.be.true('resizable');
});
});
it('with functions', () => {
it('can be set with resizable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.isResizable()).to.be.false('resizable');
if (process.platform === 'darwin') {
2020-03-20 20:28:31 +00:00
expect(w.isMaximizable()).to.to.true('maximizable');
}
2020-03-20 20:28:31 +00:00
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.isResizable()).to.be.true('resizable');
w.setResizable(false);
expect(w.isResizable()).to.be.false('resizable');
w.setResizable(true);
expect(w.isResizable()).to.be.true('resizable');
});
});
it('works for a frameless window', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, frame: false });
expect(w.resizable).to.be.true('resizable');
if (process.platform === 'win32') {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, thickFrame: false });
expect(w.resizable).to.be.false('resizable');
}
2020-03-20 20:28:31 +00:00
});
ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
const w = new BrowserWindow({
show: false,
frame: false,
resizable: false,
transparent: true
2020-03-20 20:28:31 +00:00
});
w.setContentSize(60, 60);
expectBoundsEqual(w.getContentSize(), [60, 60]);
w.setContentSize(30, 30);
expectBoundsEqual(w.getContentSize(), [30, 30]);
w.setContentSize(10, 10);
expectBoundsEqual(w.getContentSize(), [10, 10]);
});
});
describe('loading main frame state', () => {
2020-03-20 20:28:31 +00:00
let server: http.Server = null as unknown as http.Server;
let serverUrl: string = null as unknown as string;
before((done) => {
server = http.createServer((request, response) => {
2020-03-20 20:28:31 +00:00
response.end();
}).listen(0, '127.0.0.1', () => {
2020-03-20 20:28:31 +00:00
serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
done();
});
});
after(() => {
2020-03-20 20:28:31 +00:00
server.close();
});
it('is true when the main frame is loading', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.on('did-start-loading', () => {
2020-03-20 20:28:31 +00:00
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
done();
});
w.webContents.loadURL(serverUrl);
});
it('is false when only a subframe is loading', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.once('did-stop-loading', () => {
2020-03-20 20:28:31 +00:00
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
w.webContents.on('did-start-loading', () => {
2020-03-20 20:28:31 +00:00
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
done();
});
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/page2'
document.body.appendChild(iframe)
2020-03-20 20:28:31 +00:00
`);
});
w.webContents.loadURL(serverUrl);
});
it('is true when navigating to pages from the same origin', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.once('did-stop-loading', () => {
2020-03-20 20:28:31 +00:00
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
w.webContents.on('did-start-loading', () => {
2020-03-20 20:28:31 +00:00
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
done();
});
w.webContents.loadURL(`${serverUrl}/page2`);
});
w.webContents.loadURL(serverUrl);
});
});
});
ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
// Not implemented on Linux.
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
describe('movable state', () => {
it('with properties', () => {
it('can be set with movable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, movable: false });
expect(w.movable).to.be.false('movable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.movable).to.be.true('movable');
w.movable = false;
expect(w.movable).to.be.false('movable');
w.movable = true;
expect(w.movable).to.be.true('movable');
});
});
it('with functions', () => {
it('can be set with movable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, movable: false });
expect(w.isMovable()).to.be.false('movable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.isMovable()).to.be.true('movable');
w.setMovable(false);
expect(w.isMovable()).to.be.false('movable');
w.setMovable(true);
expect(w.isMovable()).to.be.true('movable');
});
});
});
describe('minimizable state', () => {
it('with properties', () => {
it('can be set with minimizable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.minimizable).to.be.false('minimizable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.minimizable).to.be.true('minimizable');
w.minimizable = false;
expect(w.minimizable).to.be.false('minimizable');
w.minimizable = true;
expect(w.minimizable).to.be.true('minimizable');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.isMinimizable()).to.be.false('movable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.isMinimizable()).to.be.true('isMinimizable');
w.setMinimizable(false);
expect(w.isMinimizable()).to.be.false('isMinimizable');
w.setMinimizable(true);
expect(w.isMinimizable()).to.be.true('isMinimizable');
});
});
});
describe('maximizable state (property)', () => {
it('with properties', () => {
it('can be set with maximizable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.maximizable).to.be.false('maximizable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.maximizable).to.be.true('maximizable');
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
it('is not affected when changing other states', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.minimizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.closable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
w.closable = true;
expect(w.maximizable).to.be.true('maximizable');
w.fullScreenable = false;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('can be set with maximizable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.isMaximizable()).to.be.false('isMaximizable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
it('is not affected when changing other states', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMinimizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setClosable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setClosable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setFullScreenable(false);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform === 'win32')('maximizable state', () => {
it('with properties', () => {
it('is reset to its former state', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.maximizable = false;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('is reset to its former state', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
it('with properties', () => {
it('can be set with fullscreenable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, fullscreenable: false });
expect(w.fullScreenable).to.be.false('fullScreenable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.fullScreenable).to.be.true('fullScreenable');
w.fullScreenable = false;
expect(w.fullScreenable).to.be.false('fullScreenable');
w.fullScreenable = true;
expect(w.fullScreenable).to.be.true('fullScreenable');
});
});
it('with functions', () => {
it('can be set with fullscreenable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, fullscreenable: false });
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
w.setFullScreenable(false);
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
w.setFullScreenable(true);
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
});
});
});
// fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
2020-03-20 20:28:31 +00:00
const tick = () => new Promise(resolve => setTimeout(resolve));
ifdescribe(process.platform === 'darwin')('kiosk state', () => {
it('can be changed with setKiosk method', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow();
w.once('enter-full-screen', async () => {
2020-03-20 20:28:31 +00:00
await tick();
w.setKiosk(false);
expect(w.isKiosk()).to.be.false('isKiosk');
});
w.once('leave-full-screen', () => {
2020-03-20 20:28:31 +00:00
done();
});
w.setKiosk(true);
expect(w.isKiosk()).to.be.true('isKiosk');
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
it('resizable flag should be set to true and restored', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ resizable: false });
w.once('enter-full-screen', async () => {
2020-03-20 20:28:31 +00:00
expect(w.resizable).to.be.true('resizable');
await tick();
w.setFullScreen(false);
});
w.once('leave-full-screen', () => {
2020-03-20 20:28:31 +00:00
expect(w.resizable).to.be.false('resizable');
done();
});
w.setFullScreen(true);
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
it('can be changed with setFullScreen method', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow();
w.once('enter-full-screen', async () => {
2020-03-20 20:28:31 +00:00
expect(w.isFullScreen()).to.be.true('isFullScreen');
await tick();
w.setFullScreen(false);
});
w.once('leave-full-screen', () => {
2020-03-20 20:28:31 +00:00
expect(w.isFullScreen()).to.be.false('isFullScreen');
done();
});
w.setFullScreen(true);
});
it('does not crash when exiting simpleFullScreen', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow();
w.setSimpleFullScreen(true);
setTimeout(() => {
2020-03-20 20:28:31 +00:00
w.setFullScreen(!w.isFullScreen());
done();
}, 1000);
});
it('should not be changed by setKiosk method', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow();
w.once('enter-full-screen', async () => {
2020-03-20 20:28:31 +00:00
expect(w.isFullScreen()).to.be.true('isFullScreen');
await tick();
w.setKiosk(true);
await tick();
w.setKiosk(false);
expect(w.isFullScreen()).to.be.true('isFullScreen');
w.setFullScreen(false);
});
w.once('leave-full-screen', () => {
2020-03-20 20:28:31 +00:00
expect(w.isFullScreen()).to.be.false('isFullScreen');
done();
});
w.setFullScreen(true);
});
});
describe('closable state', () => {
it('with properties', () => {
it('can be set with closable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, closable: false });
expect(w.closable).to.be.false('closable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.closable).to.be.true('closable');
w.closable = false;
expect(w.closable).to.be.false('closable');
w.closable = true;
expect(w.closable).to.be.true('closable');
});
});
it('with functions', () => {
it('can be set with closable constructor option', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false, closable: false });
expect(w.isClosable()).to.be.false('isClosable');
});
it('can be changed', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(w.isClosable()).to.be.true('isClosable');
w.setClosable(false);
expect(w.isClosable()).to.be.false('isClosable');
w.setClosable(true);
expect(w.isClosable()).to.be.true('isClosable');
});
});
});
describe('hasShadow state', () => {
it('returns a boolean on all platforms', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const hasShadow = w.hasShadow();
expect(hasShadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
2020-03-20 20:28:31 +00:00
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.hasShadow()).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
w.setHasShadow(true);
expect(w.hasShadow()).to.be.true('hasShadow');
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
});
});
});
describe('window.getMediaSourceId()', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('returns valid source id', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const shown = emittedOnce(w, 'show');
w.show();
await shown;
// Check format 'window:1234:0'.
2020-03-20 20:28:31 +00:00
const sourceId = w.getMediaSourceId();
expect(sourceId).to.match(/^window:\d+:\d+$/);
});
});
ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('returns valid handle', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
// The module's source code is hosted at
// https://github.com/electron/node-is-valid-window
2020-03-20 20:28:31 +00:00
const isValidWindow = require('is-valid-window');
expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
});
});
ifdescribe(process.platform === 'darwin')('previewFile', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('opens the path in Quick Look on macOS', () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
expect(() => {
2020-03-20 20:28:31 +00:00
w.previewFile(__filename);
w.closeFilePreview();
}).to.not.throw();
});
});
describe('contextIsolation option with and without sandbox option', () => {
const expectedContextData = {
preloadContext: {
preloadProperty: 'number',
pageProperty: 'undefined',
typeofRequire: 'function',
typeofProcess: 'object',
typeofArrayPush: 'function',
typeofFunctionApply: 'function',
typeofPreloadExecuteJavaScriptProperty: 'undefined'
},
pageContext: {
preloadProperty: 'undefined',
pageProperty: 'string',
typeofRequire: 'undefined',
typeofProcess: 'undefined',
typeofArrayPush: 'number',
typeofFunctionApply: 'boolean',
typeofPreloadExecuteJavaScriptProperty: 'number',
typeofOpenedWindow: 'object'
}
2020-03-20 20:28:31 +00:00
};
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('separates the page context from the Electron/preload context', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
2020-03-20 20:28:31 +00:00
});
const p = emittedOnce(ipcMain, 'isolated-world');
iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
2020-03-20 20:28:31 +00:00
});
await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
iw.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('enables context isolation on child windows', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
2020-03-20 20:28:31 +00:00
});
const browserWindowCreated = emittedOnce(app, 'browser-window-created');
iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
const [, window] = await browserWindowCreated;
expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
});
it('separates the page context from the Electron/preload context with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
2020-03-20 20:28:31 +00:00
});
const p = emittedOnce(ipcMain, 'isolated-world');
ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
2020-03-20 20:28:31 +00:00
});
await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
ws.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('supports fetch api', async () => {
const fetchWindow = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
}
2020-03-20 20:28:31 +00:00
});
const p = emittedOnce(ipcMain, 'isolated-fetch-error');
fetchWindow.loadURL('about:blank');
const [, error] = await p;
expect(error).to.equal('Failed to fetch');
});
it('doesn\'t break ipc serialization', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
2020-03-20 20:28:31 +00:00
});
const p = emittedOnce(ipcMain, 'isolated-world');
iw.loadURL('about:blank');
iw.webContents.executeJavaScript(`
const opened = window.open()
openedLocation = opened.location.href
opened.close()
window.postMessage({openedLocation}, '*')
2020-03-20 20:28:31 +00:00
`);
const [, data] = await p;
expect(data.pageContext.openedLocation).to.equal('');
});
});
describe('window.webContents.focus()', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('focuses window', (done) => {
2020-03-20 20:28:31 +00:00
const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
w1.loadURL('about:blank');
const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
w2.loadURL('about:blank');
w1.webContents.focus();
// Give focus some time to switch to w1
setTimeout(() => {
2020-03-20 20:28:31 +00:00
expect(w1.webContents.isFocused()).to.be.true('focuses window');
done();
});
});
});
2020-03-20 20:28:31 +00:00
const features = process.electronBinding('features');
ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
2020-03-20 20:28:31 +00:00
let w: BrowserWindow;
beforeEach(function () {
w = new BrowserWindow({
width: 100,
height: 100,
show: false,
webPreferences: {
backgroundThrottling: false,
offscreen: true
}
2020-03-20 20:28:31 +00:00
});
});
afterEach(closeAllWindows);
it('creates offscreen window with correct size', (done) => {
w.webContents.once('paint', function (event, rect, data) {
2020-03-20 20:28:31 +00:00
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
const size = data.getSize();
const { scaleFactor } = screen.getPrimaryDisplay();
expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
done();
});
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
it('does not crash after navigation', () => {
2020-03-20 20:28:31 +00:00
w.webContents.loadURL('about:blank');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
describe('window.webContents.isOffscreen()', () => {
it('is true for offscreen type', () => {
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
});
it('is false for regular window', () => {
2020-03-20 20:28:31 +00:00
const c = new BrowserWindow({ show: false });
expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
c.destroy();
});
});
describe('window.webContents.isPainting()', () => {
it('returns whether is currently painting', (done) => {
2019-11-01 20:37:02 +00:00
w.webContents.once('paint', function () {
2020-03-20 20:28:31 +00:00
expect(w.webContents.isPainting()).to.be.true('isPainting');
done();
});
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
});
describe('window.webContents.stopPainting()', () => {
it('stops painting', (done) => {
w.webContents.on('dom-ready', () => {
2020-03-20 20:28:31 +00:00
w.webContents.stopPainting();
expect(w.webContents.isPainting()).to.be.false('isPainting');
done();
});
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
});
describe('window.webContents.startPainting()', () => {
it('starts painting', (done) => {
w.webContents.on('dom-ready', () => {
2020-03-20 20:28:31 +00:00
w.webContents.stopPainting();
w.webContents.startPainting();
2019-11-01 20:37:02 +00:00
w.webContents.once('paint', function () {
2020-03-20 20:28:31 +00:00
expect(w.webContents.isPainting()).to.be.true('isPainting');
done();
});
});
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
});
describe('frameRate APIs', () => {
it('has default frame rate (functions)', (done) => {
2019-11-01 20:37:02 +00:00
w.webContents.once('paint', function () {
2020-03-20 20:28:31 +00:00
expect(w.webContents.getFrameRate()).to.equal(60);
done();
});
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
it('has default frame rate', (done) => {
w.webContents.once('paint', function () {
2020-03-20 20:28:31 +00:00
expect(w.webContents.frameRate).to.equal(60);
done();
});
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
it('sets custom frame rate', (done) => {
w.webContents.on('dom-ready', () => {
2020-03-20 20:28:31 +00:00
w.webContents.setFrameRate(30);
2019-11-01 20:37:02 +00:00
w.webContents.once('paint', function () {
2020-03-20 20:28:31 +00:00
expect(w.webContents.getFrameRate()).to.equal(30);
done();
});
});
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
it('sets custom frame rate', (done) => {
w.webContents.on('dom-ready', () => {
2020-03-20 20:28:31 +00:00
w.webContents.frameRate = 30;
2019-11-01 20:37:02 +00:00
w.webContents.once('paint', function () {
2020-03-20 20:28:31 +00:00
expect(w.webContents.frameRate).to.equal(30);
done();
});
});
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
});
});
});