electron/spec-main/webview-spec.ts

833 lines
29 KiB
TypeScript
Raw Normal View History

2020-03-20 20:28:31 +00:00
import * as path from 'path';
import * as url from 'url';
import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main';
2020-03-20 20:28:31 +00:00
import { closeAllWindows } from './window-helpers';
import { emittedOnce, emittedUntil } from './events-helpers';
import { ifit, delay } from './spec-helpers';
2020-03-20 20:28:31 +00:00
import { expect } from 'chai';
async function loadWebView (w: WebContents, attributes: Record<string, string>, openDevTools: boolean = false): Promise<void> {
await w.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView()
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
document.body.appendChild(webview)
webview.addEventListener('dom-ready', () => {
if (${openDevTools}) {
webview.openDevTools()
}
})
webview.addEventListener('did-finish-load', () => {
resolve()
})
})
2020-03-20 20:28:31 +00:00
`);
}
describe('<webview> tag', function () {
2020-03-20 20:28:31 +00:00
const fixtures = path.join(__dirname, '..', 'spec', 'fixtures');
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
function hideChildWindows (e: any, wc: WebContents) {
wc.on('new-window', (event, url, frameName, disposition, options) => {
options.show = false;
});
}
before(() => {
app.on('web-contents-created', hideChildWindows);
});
after(() => {
app.off('web-contents-created', hideChildWindows);
});
it('works without script tag in page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
await emittedOnce(ipcMain, 'pong');
});
it('works with sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
sandbox: true
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await emittedOnce(ipcMain, 'pong');
});
it('works with contextIsolation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await emittedOnce(ipcMain, 'pong');
});
it('works with contextIsolation + sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true,
sandbox: true
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await emittedOnce(ipcMain, 'pong');
});
it('works with Trusted Types', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-trusted-types.html'));
await emittedOnce(ipcMain, 'pong');
});
it('is disabled by default', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'module', 'preload-webview.js'),
nodeIntegration: true
}
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const webview = emittedOnce(ipcMain, 'webview');
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
const [, type] = await webview;
2020-03-20 20:28:31 +00:00
expect(type).to.equal('undefined', 'WebView still exists');
});
// FIXME(deepak1556): Ch69 follow up.
xdescribe('document.visibilityState/hidden', () => {
afterEach(() => {
2020-03-20 20:28:31 +00:00
ipcMain.removeAllListeners('pong');
});
it('updates when the window is shown after the ready-to-show event', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
const readyToShowSignal = emittedOnce(w, 'ready-to-show');
const pongSignal1 = emittedOnce(ipcMain, 'pong');
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
await pongSignal1;
const pongSignal2 = emittedOnce(ipcMain, 'pong');
await readyToShowSignal;
w.show();
const [, visibilityState, hidden] = await pongSignal2;
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
it('inherits the parent window visibility state and receives visibilitychange events', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true();
// We have to start waiting for the event
// before we ask the webContents to resize.
2020-03-20 20:28:31 +00:00
const getResponse = emittedOnce(ipcMain, 'pong');
w.webContents.emit('-window-visibility-change', 'visible');
return getResponse.then(([, visibilityState, hidden]) => {
2020-03-20 20:28:31 +00:00
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
});
});
describe('did-attach-webview event', () => {
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
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('did-attach event', () => {
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('did-attach', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
describe('did-change-theme-color event', () => {
it('emits when theme color changes', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const src = url.format({
pathname: `${fixtures.replace(/\\/g, '/')}/pages/theme-color.html`,
protocol: 'file',
slashes: true
});
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', '${src}')
webview.addEventListener('did-change-theme-color', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
// This test is flaky on WOA, so skip it there.
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads devtools extensions registered on the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
w.webContents.session.removeExtension('foo');
2020-03-20 20:28:31 +00:00
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo');
await w.webContents.session.loadExtension(extensionPath);
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'webview-devtools.html'));
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(__dirname, 'fixtures', 'blank.html')}`
}, true);
2020-03-20 20:28:31 +00:00
let childWebContentsId = 0;
app.once('web-contents-created', (e, webContents) => {
2020-03-20 20:28:31 +00:00
childWebContentsId = webContents.id;
webContents.on('devtools-opened', function () {
const showPanelIntervalId = setInterval(function () {
if (!webContents.isDestroyed() && webContents.devToolsWebContents) {
webContents.devToolsWebContents.executeJavaScript('(' + function () {
const { UI } = (window as any);
chore: bump chromium to 95.0.4612.5 (main) (#30503) * chore: bump chromium in DEPS to 94.0.4604.0 * build: 3-way merge of chromium patches * chore: bump chromium in DEPS to 94.0.4605.0 * build: 3-way merge of chromium patches * 3076040: Reland Remove delete_children RemoveAllChildViews arg Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3076040 * 3069287: Remove the remaining uses and delete the deprecated API Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3069287 * 2297212: Replace RemoveWithoutPathExpansion(.*, nullptr) with Value::RemoveKey() Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2297212 Also: https://chromium-review.googlesource.com/c/chromium/src/+/3060296 * 3082756: Change transport_security_persister_path param to be a path to a file. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/3082756 > this CL intentionally changes the name of the parameter > in the network context parameters and the order of the constructor > parameters to ensure all callers update their code to pass a full > file path rather than a path to a directory. The 'path' in this diff is already an absolute path, coming from `CHECK(base::PathService::Get(chrome::DIR_USER_DATA, &path_));` at https://github.com/electron/electron/blob/08ff1c2cbf73c8cfe6bca7976e3eddc3626678db/shell/browser/electron_browser_context.cc#L126 * iwyu: network::mojom::HttpRawHeaderPair * fixup! 3076040: Reland Remove delete_children RemoveAllChildViews arg Missed one. * 2999884: CodeHealth: Remove DictionaryValue::GetStringWithoutPathExpansion Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2999884 (example of replacing GetStringWithoutPathExpansion() w/FindStringKey()) Also: https://chromium-review.googlesource.com/c/chromium/src/+/3060296 (removal of DictionaryValue::GetStringWithoutPathExpansion) * 3059260: Remove kSameSiteByDefaultCookies and kCookiesWithoutSameSiteMustBeSecure Refs: https://chromium-review.googlesource.com/c/chromium/src/+/3059260 We had both of these in a 'disable_features' list. Since these feature have been removed upstream, remove them from our disable list, too. IMPORTANT: this commit should not be backported to older branches that still have these features, because doing so would un-disable them. * 2920890: Load reroute_info from download in-progress and history db back into DownloadItem. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2920890 * 3039323: [Clipboard API] Clipboard Custom Formats implementation Part 5. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/3039323 * chore: bump chromium in DEPS to 94.0.4606.0 * 3084502: Add a new PrintRasterizePdfDpi policy. Refs: https://chromium-review.googlesource.com/c/chromium/src/+/3084502 * chore: update patches * chore: bump chromium in DEPS to 94.0.4606.3 * chore: bump chromium in DEPS to 95.0.4608.0 * chore: bump chromium in DEPS to 95.0.4609.0 * [DevTools] Remove report_raw_headers from network::ResourceRequest https://chromium-review.googlesource.com/c/chromium/src/+/2856099 * Remove content::WebContentsObserver::OnInterfaceRequestFromFrame https://chromium-review.googlesource.com/c/chromium/src/+/3092665 * Disable kDesktopCaptureMacV2 https://chromium-review.googlesource.com/c/chromium/src/+/3069272 * Add a new PrintRasterizePdfDpi policy. https://chromium-review.googlesource.com/c/chromium/src/+/3084502 * chore: update patches * chore: bump chromium in DEPS to 95.0.4609.3 * disable `use_lld` for macos * chore: update patches * Linux: use chrome_crashpad_handler instead of crashpad_handler https://chromium-review.googlesource.com/c/chromium/src/+/3054290 * chore: fix lint * Revert "[DevTools] Remove report_raw_headers from network::ResourceRequest" This reverts commit 28f4da1582d046e96cb58f3cbb590503e89dfd0d. * [DevTools] Remove report_raw_headers from network::ResourceRequest (Attempt #2) https://chromium-review.googlesource.com/c/chromium/src/+/2856099 * DCHECK that predictor always has a non-empty NetworkIsolationKey. https://chromium-review.googlesource.com/c/chromium/src/+/3067698 * Remove --no-untrusted-code-mitigations from //content and //gin https://chromium-review.googlesource.com/c/chromium/src/+/3096585 * fixup! Remove kSameSiteByDefaultCookies and kCookiesWithoutSameSiteMustBeSecure https://chromium-review.googlesource.com/c/chromium/src/+/3059260 * fixup! Remove kSameSiteByDefaultCookies and kCookiesWithoutSameSiteMustBeSecure * Convert PrintManager to RenderFrameHostReceiverSet. https://chromium-review.googlesource.com/c/chromium/src/+/3072019 * chore: bump chromium in DEPS to 95.0.4612.5 * chore: disable v8 oilpan * [Compiler] Remove untrusted code mitigations. https://chromium-review.googlesource.com/c/v8/v8/+/3045704 * Remove most FTP logic from services/network. https://chromium-review.googlesource.com/c/chromium/src/+/3076119 * Rename scale_factor.h -> resource_scale_factor.h https://chromium-review.googlesource.com/c/chromium/src/+/3057113 * [GURL -> SiteForCookies] extensions/ https://chromium-review.googlesource.com/c/chromium/src/+/3100825 * breadcrumbs: add desktop entry point https://chromium-review.googlesource.com/c/chromium/src/+/3021746 * Move args_ to private in ExtensionFunction https://chromium-review.googlesource.com/c/chromium/src/+/3076261 * chore: iwyu * fixup! Remove kSameSiteByDefaultCookies and kCookiesWithoutSameSiteMustBeSecure * Disable kDesktopCaptureMacV2 https://chromium-review.googlesource.com/c/chromium/src/+/3069272 * fixup! [Compiler] Remove untrusted code mitigations. * fixup! Disable kDesktopCaptureMacV2 * Revert "chore: disable v8 oilpan" This reverts commit 5d255cf1d8e8efbb906047937a713279e5f800d0. * Reland "chore: disable v8 oilpan" This reverts commit 1c252765b07a205560e7b5eed06de2605336e2d8. The previous revert was to test on which platforms did the heapsnapshot test actually fail. * [Clipboard API] Clipboard Custom Formats implementation Part 5. https://chromium-review.googlesource.com/c/chromium/src/+/3039323 * Convert ExtensionFrameHost to RenderFrameHostReceiverSet. https://chromium-review.googlesource.com/c/chromium/src/+/3063358 * Convert PDFWebContentsHelper to RenderFrameHostReceiverSet. https://chromium-review.googlesource.com/c/chromium/src/+/3049751 * [Underscore Migration] Migrate ui/legacy https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3093160 * chore: remove unknown permission error * chore: fix lint * chore: ignore -Wunreachable-code-return for node deps/ * fixup! chore: ignore -Wunreachable-code-return for node deps/ * fix: windows build * fix: build dependency Dependency was missed in cbeae20438be8baf03ce0e32a73563a80aeccb37 * 3108669: arm,dsp: Fix 8bpp Dct64_NEON(). https://chromium-review.googlesource.com/c/codecs/libgav1/+/3108669 * chore: revert libgav1 roll * Revert "3108669: arm,dsp: Fix 8bpp Dct64_NEON()." This reverts commit 7ed31323127aac8ba2eaff9cae6c9be9a4954f33. * Revert "chore: revert libgav1 roll" This reverts commit 084a490d298811267316c786762fe7aa91b6318d. * chore: revert clang roll * chore: Fix -Wunreachable-code-aggressive warnings in arm and arm64 code Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: mlaurencin <mlaurencin@electronjs.org> Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
2021-08-24 00:52:17 +00:00
const tabs = UI.inspectorView.tabbedPane.tabs;
const lastPanelId: any = tabs[tabs.length - 1].id;
UI.inspectorView.showPanel(lastPanelId);
2020-03-20 20:28:31 +00:00
}.toString() + ')()');
} else {
2020-03-20 20:28:31 +00:00
clearInterval(showPanelIntervalId);
}
2020-03-20 20:28:31 +00:00
}, 100);
});
});
2020-03-20 20:28:31 +00:00
const [, { runtimeId, tabId }] = await emittedOnce(ipcMain, 'answer');
expect(runtimeId).to.match(/^[a-z]{32}$/);
expect(tabId).to.equal(childWebContentsId);
});
describe('zoom behavior', () => {
2020-03-20 20:28:31 +00:00
const zoomScheme = standardScheme;
const webviewSession = session.fromPartition('webview-temp');
before(() => {
2020-03-20 20:28:31 +00:00
const protocol = webviewSession.protocol;
protocol.registerStringProtocol(zoomScheme, (request, callback) => {
2020-03-20 20:28:31 +00:00
callback('hello');
});
2020-03-20 20:28:31 +00:00
});
after(() => {
2020-03-20 20:28:31 +00:00
const protocol = webviewSession.protocol;
protocol.unregisterProtocol(zoomScheme);
2020-03-20 20:28:31 +00:00
});
it('inherits the zoomFactor of the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
const zoomEventPromise = emittedOnce(ipcMain, 'webview-parent-zoom-level');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-factor.html'));
2020-03-20 20:28:31 +00:00
const [, zoomFactor, zoomLevel] = await zoomEventPromise;
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
});
it('maintains zoom level on navigation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-level', (event, zoomLevel, zoomFactor, newHost, final) => {
if (!newHost) {
2020-03-20 20:28:31 +00:00
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
} else {
2020-03-20 20:28:31 +00:00
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
}
if (final) {
2020-03-20 20:28:31 +00:00
resolve();
}
2020-03-20 20:28:31 +00:00
});
});
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(fixtures, 'pages', 'webview-custom-zoom-level.html'));
2020-03-20 20:28:31 +00:00
await promise;
});
it('maintains zoom level when navigating within same page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-in-page', (event, zoomLevel, zoomFactor, final) => {
2020-03-20 20:28:31 +00:00
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
if (final) {
2020-03-20 20:28:31 +00:00
resolve();
}
2020-03-20 20:28:31 +00:00
});
});
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(fixtures, 'pages', 'webview-in-page-navigate.html'));
2020-03-20 20:28:31 +00:00
await promise;
});
it('inherits zoom level for the origin when available', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixtures, 'pages', 'webview-origin-zoom-level.html'));
2020-03-20 20:28:31 +00:00
const [, zoomLevel] = await emittedOnce(ipcMain, 'webview-origin-zoom-level');
expect(zoomLevel).to.equal(2.0);
});
it('does not crash when navigating with zoom level inherited from parent', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = emittedOnce(w.webContents, 'did-attach-webview');
const readyPromise = emittedOnce(ipcMain, 'dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
const [, webview] = await attachPromise;
await readyPromise;
expect(webview.getZoomFactor()).to.equal(1.2);
await w.loadURL(`${zoomScheme}://host1`);
});
it('does not crash when changing zoom level after webview is destroyed', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = emittedOnce(w.webContents, 'did-attach-webview');
await w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
await attachPromise;
await w.webContents.executeJavaScript('view.remove()');
w.webContents.setZoomLevel(0.5);
});
2020-03-20 20:28:31 +00:00
});
describe('requestFullscreen from webview', () => {
const loadWebViewWindow = async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const attachPromise = emittedOnce(w.webContents, 'did-attach-webview');
const readyPromise = emittedOnce(ipcMain, 'webview-ready');
w.loadFile(path.join(__dirname, 'fixtures', 'webview', 'fullscreen', 'main.html'));
const [, webview] = await attachPromise;
await readyPromise;
return [w, webview];
};
afterEach(closeAllWindows);
it('should make parent frame element fullscreen too', async () => {
const [w, webview] = await loadWebViewWindow();
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
const parentFullscreen = emittedOnce(ipcMain, 'fullscreenchange');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await parentFullscreen;
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
});
// FIXME(zcbenz): Fullscreen events do not work on Linux.
// This test is flaky on arm64 macOS.
ifit(process.platform !== 'linux' && process.arch !== 'arm64')('exiting fullscreen should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = emittedOnce(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
await webview.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
await delay(0);
expect(w.isFullScreen()).to.be.false();
});
// Sending ESC via sendInputEvent only works on Windows.
ifit(process.platform === 'win32')('pressing ESC should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = emittedOnce(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFullScreen;
await delay(0);
expect(w.isFullScreen()).to.be.false();
});
it('pressing ESC should emit the leave-html-full-screen event', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview');
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const enterFSWindow = emittedOnce(w, 'enter-html-full-screen');
const enterFSWebview = emittedOnce(webContents, 'enter-html-full-screen');
await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFSWindow;
await enterFSWebview;
const leaveFSWindow = emittedOnce(w, 'leave-html-full-screen');
const leaveFSWebview = emittedOnce(webContents, 'leave-html-full-screen');
webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFSWindow;
await leaveFSWebview;
});
});
describe('child windows', () => {
2020-03-20 20:28:31 +00:00
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
2020-03-20 20:28:31 +00:00
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('opens window of about:blank with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}`
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const [, content] = await emittedOnce(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-file.html')}`
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const [, content] = await emittedOnce(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('returns null from window.open when allowpopups is not set', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-no-allowpopups.html')}`
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const [, { windowOpenReturnedNull }] = await emittedOnce(ipcMain, 'answer');
expect(windowOpenReturnedNull).to.be.true();
});
it('blocks accessing cross-origin frames', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}`
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const [, content] = await emittedOnce(ipcMain, 'answer');
const expectedContent =
2020-03-20 20:28:31 +00:00
'Blocked a frame with origin "file://" from accessing a cross-origin frame.';
2020-03-20 20:28:31 +00:00
expect(content).to.equal(expectedContent);
});
it('emits a new-window event', async () => {
// Don't wait for loading to finish.
const attributes = {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
2020-03-20 20:28:31 +00:00
};
const { url, frameName } = await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = document.createElement('webview')
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
document.body.appendChild(webview)
webview.addEventListener('new-window', (e) => {
resolve({url: e.url, frameName: e.frameName})
})
})
2020-03-20 20:28:31 +00:00
`);
2020-03-20 20:28:31 +00:00
expect(url).to.equal('http://host/');
expect(frameName).to.equal('host');
});
it('emits a browser-window-created event', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
await emittedOnce(app, 'browser-window-created');
});
it('emits a web-contents-created event', async () => {
const webContentsCreated = emittedUntil(app, 'web-contents-created',
(event: Electron.Event, contents: Electron.WebContents) => contents.getType() === 'window');
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
2020-03-20 20:28:31 +00:00
});
await webContentsCreated;
2020-03-20 20:28:31 +00:00
});
it('does not crash when creating window with noopener', async () => {
loadWebView(w.webContents, {
allowpopups: 'on',
src: `file://${path.join(fixtures, 'api', 'native-window-open-noopener.html')}`
});
await emittedOnce(app, 'browser-window-created');
});
2020-03-20 20:28:31 +00:00
});
describe('webpreferences attribute', () => {
2020-03-20 20:28:31 +00:00
let w: BrowserWindow;
beforeEach(async () => {
2020-03-20 20:28:31 +00:00
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
2019-11-01 20:37:02 +00:00
it('can enable context isolation', async () => {
loadWebView(w.webContents, {
allowpopups: 'yes',
preload: `file://${fixtures}/api/isolated-preload.js`,
src: `file://${fixtures}/api/isolated.html`,
webpreferences: 'contextIsolation=yes'
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const [, data] = await emittedOnce(ipcMain, 'isolated-world');
expect(data).to.deep.equal({
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
});
});
});
describe('permission request handlers', () => {
2020-03-20 20:28:31 +00:00
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
2020-03-20 20:28:31 +00:00
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
2020-03-20 20:28:31 +00:00
const partition = 'permissionTest';
2019-11-01 20:37:02 +00:00
function setUpRequestHandler (webContentsId: number, requestedPermission: string) {
return new Promise<void>((resolve, reject) => {
session.fromPartition(partition).setPermissionRequestHandler(function (webContents, permission, callback) {
if (webContents.id === webContentsId) {
// requestMIDIAccess with sysex requests both midi and midiSysex so
// grant the first midi one and then reject the midiSysex one
if (requestedPermission === 'midiSysex' && permission === 'midi') {
2020-03-20 20:28:31 +00:00
return callback(true);
}
try {
2020-03-20 20:28:31 +00:00
expect(permission).to.equal(requestedPermission);
} catch (e) {
2020-03-20 20:28:31 +00:00
return reject(e);
}
2020-03-20 20:28:31 +00:00
callback(false);
resolve();
}
2020-03-20 20:28:31 +00:00
});
});
}
afterEach(() => {
2020-03-20 20:28:31 +00:00
session.fromPartition(partition).setPermissionRequestHandler(null);
});
// This is disabled because CI machines don't have cameras or microphones,
// so Chrome responds with "NotFoundError" instead of
// "PermissionDeniedError". It should be re-enabled if we find a way to mock
// the presence of a microphone & camera.
xit('emits when using navigator.getUserMedia api', async () => {
2020-03-20 20:28:31 +00:00
const errorFromRenderer = emittedOnce(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/media.html`,
partition,
nodeintegration: 'on'
2020-03-20 20:28:31 +00:00
});
const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
setUpRequestHandler(webViewContents.id, 'media');
const [, errorName] = await errorFromRenderer;
expect(errorName).to.equal('PermissionDeniedError');
});
it('emits when using navigator.geolocation api', async () => {
2020-03-20 20:28:31 +00:00
const errorFromRenderer = emittedOnce(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/geolocation.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
2020-03-20 20:28:31 +00:00
});
const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
setUpRequestHandler(webViewContents.id, 'geolocation');
const [, error] = await errorFromRenderer;
expect(error).to.equal('User denied Geolocation');
});
it('emits when using navigator.requestMIDIAccess without sysex api', async () => {
2020-03-20 20:28:31 +00:00
const errorFromRenderer = emittedOnce(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
2020-03-20 20:28:31 +00:00
});
const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
setUpRequestHandler(webViewContents.id, 'midi');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when using navigator.requestMIDIAccess with sysex api', async () => {
2020-03-20 20:28:31 +00:00
const errorFromRenderer = emittedOnce(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi-sysex.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
2020-03-20 20:28:31 +00:00
});
const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
setUpRequestHandler(webViewContents.id, 'midiSysex');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when accessing external protocol', async () => {
loadWebView(w.webContents, {
src: 'magnet:test',
2019-11-01 20:37:02 +00:00
partition
2020-03-20 20:28:31 +00:00
});
const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
await setUpRequestHandler(webViewContents.id, 'openExternal');
});
it('emits when using Notification.requestPermission', async () => {
2020-03-20 20:28:31 +00:00
const errorFromRenderer = emittedOnce(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/notification.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
2020-03-20 20:28:31 +00:00
});
const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
2020-03-20 20:28:31 +00:00
await setUpRequestHandler(webViewContents.id, 'notifications');
2020-03-20 20:28:31 +00:00
const [, error] = await errorFromRenderer;
expect(error).to.equal('denied');
});
});
describe('DOM events', () => {
afterEach(closeAllWindows);
it('receives extra properties on DOM events when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'data:text/html,<script>console.log("hi")</script>')
webview.addEventListener('console-message', (e) => {
resolve(e.message)
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('hi');
});
it('emits focus event when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('dom-ready', () => {
webview.focus()
})
webview.addEventListener('focus', () => {
resolve();
})
document.body.appendChild(webview)
})`);
});
});
2020-03-20 20:28:31 +00:00
});