electron/spec-main/chromium-spec.ts

2199 lines
84 KiB
TypeScript
Raw Normal View History

2020-03-20 20:28:31 +00:00
import { expect } from 'chai';
feat: add support for WebHID (#30213) * feat: add support for WebHID * Apply suggestions from code review Co-authored-by: Jeremy Rose <jeremya@chromium.org> * Address review feedback * Address review feedback * chore: clear granted_devices on navigation Also added test to verify devices get cleared * fixup testing for device clear * make sure navigator.hid.getDevices is run on correct frame * clear granted devices on RenderFrameHost deletion/change * manage device permissions per RenderFrameHost This change makes sure we don't clear device permission prematurely due to child frame navigation * Update shell/browser/api/electron_api_web_contents.cc Co-authored-by: Jeremy Rose <jeremya@chromium.org> * apply review feedback from @zcbenz * Match upstream ObjectMap This change matches what ObjectPermissionContextBase uses to cache object permissions: https://source.chromium.org/chromium/chromium/src/+/main:components/permissions/object_permission_context_base.h;l=52;drc=8f95b5eab2797a3e26bba299f3b0df85bfc98bf5;bpv=1;bpt=0 The main reason for this was to resolve this crash on Win x64: ok 2 WebContentsView doesn't crash when GCed during allocation Received fatal exception EXCEPTION_ACCESS_VIOLATION Backtrace: gin::WrappableBase::SecondWeakCallback [0x00007FF6F2AFA005+133] (o:\gin\wrappable.cc:53) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacks [0x00007FF6F028F9AB+171] (o:\v8\src\handles\global-handles.cc:1400) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacksFromTask [0x00007FF6F028F867+391] (o:\v8\src\handles\global-handles.cc:1387) node::PerIsolatePlatformData::RunForegroundTask [0x00007FF6F3B4D065+317] (o:\third_party\electron_node\src\node_platform.cc:415) node::PerIsolatePlatformData::FlushForegroundTasksInternal [0x00007FF6F3B4C424+776] (o:\third_party\electron_node\src\node_platform.cc:479) uv_run [0x00007FF6F2DDD07C+492] (o:\third_party\electron_node\deps\uv\src\win\core.c:609) electron::NodeBindings::UvRunOnce [0x00007FF6EEE1E036+294] (o:\electron\shell\common\node_bindings.cc:631) base::TaskAnnotator::RunTask [0x00007FF6F2318A19+457] (o:\base\task\common\task_annotator.cc:178) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl [0x00007FF6F2E6F553+963] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:361) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork [0x00007FF6F2E6EC69+137] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:266) base::MessagePumpForUI::DoRunLoop [0x00007FF6F235AA58+216] (o:\base\message_loop\message_pump_win.cc:221) base::MessagePumpWin::Run [0x00007FF6F235A01A+106] (o:\base\message_loop\message_pump_win.cc:79) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run [0x00007FF6F2E702DA+682] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:470) base::RunLoop::Run [0x00007FF6F22F95BA+842] (o:\base\run_loop.cc:136) content::BrowserMainLoop::RunMainMessageLoop [0x00007FF6F14423CC+208] (o:\content\browser\browser_main_loop.cc:990) content::BrowserMainRunnerImpl::Run [0x00007FF6F144402F+143] (o:\content\browser\browser_main_runner_impl.cc:153) content::BrowserMain [0x00007FF6F143F911+257] (o:\content\browser\browser_main.cc:49) content::RunBrowserProcessMain [0x00007FF6EFFA7D18+112] (o:\content\app\content_main_runner_impl.cc:608) content::ContentMainRunnerImpl::RunBrowser [0x00007FF6EFFA8CF4+1220] (o:\content\app\content_main_runner_impl.cc:1104) content::ContentMainRunnerImpl::Run [0x00007FF6EFFA87C9+393] (o:\content\app\content_main_runner_impl.cc:971) content::RunContentProcess [0x00007FF6EFFA73BD+733] (o:\content\app\content_main.cc:394) content::ContentMain [0x00007FF6EFFA79E1+54] (o:\content\app\content_main.cc:422) wWinMain [0x00007FF6EECA1535+889] (o:\electron\shell\app\electron_main.cc:291) __scrt_common_main_seh [0x00007FF6F6F88482+262] (d:\A01\_work\6\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288) BaseThreadInitThunk [0x00007FFEC0087034+20] RtlUserThreadStart [0x00007FFEC1F02651+33] ✗ Electron tests failed with code 0xc0000005. Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2021-09-23 11:00:11 +00:00
import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main';
import { emittedOnce } from './events-helpers';
2020-03-20 20:28:31 +00:00
import { closeAllWindows } from './window-helpers';
import * as https from 'https';
import * as http from 'http';
import * as path from 'path';
import * as fs from 'fs';
import * as url from 'url';
import * as ChildProcess from 'child_process';
import { EventEmitter } from 'events';
import { promisify } from 'util';
import { ifit, ifdescribe, defer, delay } from './spec-helpers';
2020-03-20 20:28:31 +00:00
import { AddressInfo } from 'net';
import { PipeTransport } from './pipe-transport';
2020-03-20 20:28:31 +00:00
const features = process._linkedBinding('electron_common_features');
2020-03-20 20:28:31 +00:00
const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures');
2019-05-29 23:33:19 +00:00
describe('reporting api', () => {
// TODO(nornagon): this started failing a lot on CI. Figure out why and fix
// it.
it.skip('sends a report for a deprecation', async () => {
2020-03-20 20:28:31 +00:00
const reports = new EventEmitter();
2019-05-29 23:33:19 +00:00
// The Reporting API only works on https with valid certs. To dodge having
// to set up a trusted certificate, hack the validator.
session.defaultSession.setCertificateVerifyProc((req, cb) => {
2020-03-20 20:28:31 +00:00
cb(0);
});
const certPath = path.join(fixturesPath, 'certificates');
2019-05-29 23:33:19 +00:00
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
requestCert: true,
rejectUnauthorized: false
2020-03-20 20:28:31 +00:00
};
2019-05-29 23:33:19 +00:00
const server = https.createServer(options, (req, res) => {
if (req.url === '/report') {
2020-03-20 20:28:31 +00:00
let data = '';
req.on('data', (d) => { data += d.toString('utf-8'); });
2019-05-29 23:33:19 +00:00
req.on('end', () => {
2020-03-20 20:28:31 +00:00
reports.emit('report', JSON.parse(data));
});
2019-05-29 23:33:19 +00:00
}
res.setHeader('Report-To', JSON.stringify({
group: 'default',
max_age: 120,
endpoints: [{ url: `https://localhost:${(server.address() as any).port}/report` }]
2020-03-20 20:28:31 +00:00
}));
res.setHeader('Content-Type', 'text/html');
2019-05-29 23:33:19 +00:00
// using the deprecated `webkitRequestAnimationFrame` will trigger a
// "deprecation" report.
2020-03-20 20:28:31 +00:00
res.end('<script>webkitRequestAnimationFrame(() => {})</script>');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
2019-05-29 23:33:19 +00:00
const bw = new BrowserWindow({
2019-11-01 20:37:02 +00:00
show: false
2020-03-20 20:28:31 +00:00
});
2019-05-29 23:33:19 +00:00
try {
2020-03-20 20:28:31 +00:00
const reportGenerated = emittedOnce(reports, 'report');
const url = `https://localhost:${(server.address() as any).port}/a`;
await bw.loadURL(url);
const [report] = await reportGenerated;
expect(report).to.be.an('array');
expect(report[0].type).to.equal('deprecation');
expect(report[0].url).to.equal(url);
expect(report[0].body.id).to.equal('PrefixedRequestAnimationFrame');
2019-05-29 23:33:19 +00:00
} finally {
2020-03-20 20:28:31 +00:00
bw.destroy();
server.close();
2019-05-29 23:33:19 +00:00
}
2020-03-20 20:28:31 +00:00
});
});
describe('window.postMessage', () => {
afterEach(async () => {
2020-03-20 20:28:31 +00:00
await closeAllWindows();
});
it('sets the source and origin correctly', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
const [, message] = await emittedOnce(ipcMain, 'complete');
expect(message.data).to.equal('testing');
expect(message.origin).to.equal('file://');
expect(message.sourceEqualsOpener).to.equal(true);
expect(message.eventOrigin).to.equal('file://');
});
2020-03-20 20:28:31 +00:00
});
describe('focus handling', () => {
2020-03-20 20:28:31 +00:00
let webviewContents: WebContents = null as unknown as WebContents;
let w: BrowserWindow = null as unknown as BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({
show: true,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const webviewReady = emittedOnce(w.webContents, 'did-attach-webview');
await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
const [, wvContents] = await webviewReady;
webviewContents = wvContents;
await emittedOnce(webviewContents, 'did-finish-load');
w.focus();
});
afterEach(() => {
2020-03-20 20:28:31 +00:00
webviewContents = null as unknown as WebContents;
w.destroy();
w = null as unknown as BrowserWindow;
});
const expectFocusChange = async () => {
2020-03-20 20:28:31 +00:00
const [, focusedElementId] = await emittedOnce(ipcMain, 'focus-changed');
return focusedElementId;
};
describe('a TAB press', () => {
const tabPressEvent: any = {
type: 'keyDown',
keyCode: 'Tab'
2020-03-20 20:28:31 +00:00
};
it('moves focus to the next focusable item', async () => {
2020-03-20 20:28:31 +00:00
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
});
});
describe('a SHIFT + TAB press', () => {
const shiftTabPressEvent: any = {
type: 'keyDown',
modifiers: ['Shift'],
keyCode: 'Tab'
2020-03-20 20:28:31 +00:00
};
it('moves focus to the previous focusable item', async () => {
2020-03-20 20:28:31 +00:00
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
});
});
});
describe('web security', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
2020-03-20 20:28:31 +00:00
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
2020-03-20 20:28:31 +00:00
serverUrl = `http://localhost:${(server.address() as any).port}`;
});
after(() => {
2020-03-20 20:28:31 +00:00
server.close();
});
it('engages CORB when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
2020-03-20 20:28:31 +00:00
const p = emittedOnce(ipcMain, 'success');
await w.loadURL(`data:text/html,<script>
const s = document.createElement('script')
s.src = "${serverUrl}"
// The script will load successfully but its body will be emptied out
// by CORB, so we don't expect a syntax error.
s.onload = () => { require('electron').ipcRenderer.send('success') }
document.documentElement.appendChild(s)
2020-03-20 20:28:31 +00:00
</script>`);
await p;
});
it('bypasses CORB when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
2020-03-20 20:28:31 +00:00
const p = emittedOnce(ipcMain, 'success');
await w.loadURL(`data:text/html,
<script>
window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
</script>
2020-03-20 20:28:31 +00:00
<script src="${serverUrl}"></script>`);
await p;
});
it('engages CORS when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = emittedOnce(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('failed');
});
it('bypasses CORS when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = emittedOnce(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('passed');
});
describe('accessing file://', () => {
async function loadFile (w: BrowserWindow) {
const thisFile = url.format({
pathname: __filename.replace(/\\/g, '/'),
protocol: 'file',
slashes: true
});
await w.loadURL(`data:text/html,<script>
function loadFile() {
return new Promise((resolve) => {
fetch('${thisFile}').then(
() => resolve('loaded'),
() => resolve('failed')
)
});
}
</script>`);
return await w.webContents.executeJavaScript('loadFile()');
}
it('is forbidden when web security is enabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
const result = await loadFile(w);
expect(result).to.equal('failed');
});
it('is allowed when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
const result = await loadFile(w);
expect(result).to.equal('loaded');
});
});
describe('wasm-eval csp', () => {
async function loadWasm (csp: string) {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
enableBlinkFeatures: 'WebAssemblyCSP'
}
});
await w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
</head>
<script>
function loadWasm() {
const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
return new Promise((resolve) => {
WebAssembly.instantiate(wasmBin).then(() => {
resolve('loaded')
}).catch((error) => {
resolve(error.message)
})
});
}
</script>`);
return await w.webContents.executeJavaScript('loadWasm()');
}
it('wasm codegen is disallowed by default', async () => {
const r = await loadWasm('');
expect(r).to.equal('WebAssembly.instantiate(): Wasm code generation disallowed by embedder');
});
it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
const r = await loadWasm("'wasm-unsafe-eval'");
expect(r).to.equal('loaded');
});
});
it('does not crash when multiple WebContent are created with web security disabled', () => {
const options = { show: false, webPreferences: { webSecurity: false } };
const w1 = new BrowserWindow(options);
w1.loadURL(serverUrl);
const w2 = new BrowserWindow(options);
w2.loadURL(serverUrl);
});
2020-03-20 20:28:31 +00:00
});
describe('command line switches', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
describe('--lang switch', () => {
2020-03-20 20:28:31 +00:00
const currentLocale = app.getLocale();
const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'locale-check');
const args = [appPath, `--set-lang=${locale}`];
if (printEnv) {
args.push('--print-env');
}
appProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
2020-03-20 20:28:31 +00:00
appProcess.stdout.on('data', (data) => { output += data; });
let stderr = '';
appProcess.stderr.on('data', (data) => { stderr += data; });
const [code, signal] = await emittedOnce(appProcess, 'exit');
if (code !== 0) {
throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
}
output = output.replace(/(\r\n|\n|\r)/gm, '');
expect(output).to.equal(result);
2020-03-20 20:28:31 +00:00
};
it('should set the locale', async () => testLocale('fr', 'fr'));
it('should not set an invalid locale', async () => testLocale('asdfkl', currentLocale));
const lcAll = String(process.env.LC_ALL);
ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
// The LC_ALL env should not be set to DOM locale string.
expect(lcAll).to.not.equal(app.getLocale());
});
ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
2020-03-20 20:28:31 +00:00
});
describe('--remote-debugging-pipe switch', () => {
it('should expose CDP via pipe', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(message.result.product).to.contain('Chrome');
expect(message.result.userAgent).to.contain('Electron');
});
it('should override --remote-debugging-port switch', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
let stderr = '';
appProcess.stderr.on('data', (data: string) => { stderr += data; });
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(stderr).to.not.include('DevTools listening on');
});
it('should shut down Electron upon Browser.close CDP command', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
pipe.send({ id: 1, method: 'Browser.close', params: {} });
await new Promise(resolve => { appProcess!.on('exit', resolve); });
});
});
describe('--remote-debugging-port switch', () => {
it('should display the discovery page', (done) => {
2020-03-20 20:28:31 +00:00
const electronPath = process.execPath;
let output = '';
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
appProcess.stdout.on('data', (data) => {
console.log(data);
});
appProcess.stderr.on('data', (data) => {
console.log(data);
2020-03-20 20:28:31 +00:00
output += data;
const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
if (m) {
appProcess!.stderr.removeAllListeners('data');
2020-03-20 20:28:31 +00:00
const port = m[1];
http.get(`http://127.0.0.1:${port}`, (res) => {
try {
expect(res.statusCode).to.eql(200);
expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
done();
} catch (e) {
done(e);
} finally {
res.destroy();
}
2020-03-20 20:28:31 +00:00
});
}
2020-03-20 20:28:31 +00:00
});
});
});
});
describe('chromium features', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
describe('accessing key names also used as Node.js module names', () => {
it('does not crash', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
});
});
describe('loading jquery', () => {
it('does not crash', (done) => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
});
});
describe('navigator.languages', () => {
it('should return the system locale only', async () => {
2020-03-20 20:28:31 +00:00
const appLocale = app.getLocale();
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const languages = await w.webContents.executeJavaScript('navigator.languages');
expect(languages.length).to.be.greaterThan(0);
expect(languages).to.contain(appLocale);
2020-03-20 20:28:31 +00:00
});
});
describe('navigator.serviceWorker', () => {
it('should register for file scheme', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
2020-03-20 20:28:31 +00:00
w.webContents.reload();
} else if (channel === 'error') {
2020-03-20 20:28:31 +00:00
done(message);
} else if (channel === 'response') {
2020-03-20 20:28:31 +00:00
expect(message).to.equal('Hello from serviceWorker!');
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
2020-03-20 20:28:31 +00:00
}).then(() => done());
}
2020-03-20 20:28:31 +00:00
});
w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for intercepted file scheme', (done) => {
2020-03-20 20:28:31 +00:00
const customSession = session.fromPartition('intercept-file');
customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
2020-03-20 20:28:31 +00:00
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
2020-03-20 20:28:31 +00:00
const content = fs.readFileSync(path.normalize(file));
const ext = path.extname(file);
let type = 'text/html';
2020-03-20 20:28:31 +00:00
if (ext === '.js') type = 'application/javascript';
callback({ data: content, mimeType: type } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
2020-03-20 20:28:31 +00:00
w.webContents.reload();
} else if (channel === 'error') {
2020-03-20 20:28:31 +00:00
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
2020-03-20 20:28:31 +00:00
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol('file');
done();
2020-03-20 20:28:31 +00:00
});
}
2020-03-20 20:28:31 +00:00
});
w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for custom scheme', (done) => {
const customSession = session.fromPartition('custom-scheme');
customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
callback({ path: path.normalize(file) } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
done();
});
}
});
w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
});
it('should not crash when nodeIntegration is enabled', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
partition: 'sw-file-scheme-worker-spec',
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
session.fromPartition('sw-file-scheme-worker-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
2020-03-20 20:28:31 +00:00
});
describe('navigator.geolocation', () => {
before(function () {
if (!features.isFakeLocationProviderEnabled()) {
2020-03-20 20:28:31 +00:00
return this.skip();
}
2020-03-20 20:28:31 +00:00
});
it('returns error when permission is denied', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'geolocation-spec',
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
const message = emittedOnce(w.webContents, 'ipc-message');
w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'geolocation') {
2020-03-20 20:28:31 +00:00
callback(false);
} else {
2020-03-20 20:28:31 +00:00
callback(true);
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
const [, channel] = await message;
expect(channel).to.equal('success', 'unexpected response from geolocation api');
2020-03-20 20:28:31 +00:00
});
});
describe('web workers', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
appProcess = ChildProcess.spawn(process.execPath, [appPath]);
const [code] = await emittedOnce(appProcess, 'exit');
expect(code).to.equal(0);
});
});
describe('form submit', () => {
2020-03-20 20:28:31 +00:00
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
2020-03-20 20:28:31 +00:00
let body = '';
req.on('data', (chunk) => {
2020-03-20 20:28:31 +00:00
body += chunk;
});
res.setHeader('Content-Type', 'application/json');
req.on('end', () => {
2020-03-20 20:28:31 +00:00
res.end(`body:${body}`);
});
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
2020-03-20 20:28:31 +00:00
serverUrl = `http://localhost:${(server.address() as any).port}`;
});
after(async () => {
2020-03-20 20:28:31 +00:00
server.close();
await closeAllWindows();
});
[true, false].forEach((isSandboxEnabled) =>
describe(`sandbox=${isSandboxEnabled}`, () => {
it('posts data in the same window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
2020-03-20 20:28:31 +00:00
const loadPromise = emittedOnce(w.webContents, 'did-finish-load');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.submit();
2020-03-20 20:28:31 +00:00
`);
2020-03-20 20:28:31 +00:00
await loadPromise;
2020-03-20 20:28:31 +00:00
const res = await w.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
it('posts data to a new window with target=_blank', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
2020-03-20 20:28:31 +00:00
const windowCreatedPromise = emittedOnce(app, 'browser-window-created');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.target = '_blank';
form.submit();
2020-03-20 20:28:31 +00:00
`);
2020-03-20 20:28:31 +00:00
const [, newWin] = await windowCreatedPromise;
2020-03-20 20:28:31 +00:00
const res = await newWin.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
})
2020-03-20 20:28:31 +00:00
);
});
describe('window.open', () => {
for (const show of [true, false]) {
it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show });
// toggle visibility
if (show) {
2020-03-20 20:28:31 +00:00
w.hide();
} else {
2020-03-20 20:28:31 +00:00
w.show();
}
defer(() => { w.close(); });
const promise = emittedOnce(app, 'browser-window-created');
2020-03-20 20:28:31 +00:00
w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
const [, newWindow] = await promise;
expect(newWindow.isVisible()).to.equal(true);
2020-03-20 20:28:31 +00:00
});
}
it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
// NB. webSecurity is disabled because native window.open() is not
// allowed to load devtools:// URLs.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
2020-03-20 20:28:31 +00:00
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
2020-03-20 20:28:31 +00:00
`);
const [, contents] = await emittedOnce(app, 'web-contents-created');
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
it('can disable node integration when it is enabled on the parent window', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await emittedOnce(app, 'web-contents-created');
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
chore: bump chromium to 100.0.4894.0 (main) (#32852) * chore: bump chromium in DEPS to 100.0.4880.0 * resolve conflicts * chore: update patches * fix patch * PIP20: add a new DocumentOverlayWindowViews subtype https://chromium-review.googlesource.com/c/chromium/src/+/3252789 * Clean up PictureInPictureWindowManager::EnterPictureInPicture() https://chromium-review.googlesource.com/c/chromium/src/+/3424145 * Remove StoragePartitionId. https://chromium-review.googlesource.com/c/chromium/src/+/2811120 * Remove FLoC code https://chromium-review.googlesource.com/c/chromium/src/+/3424359 * media: Make AddSupportedKeySystems() Async https://chromium-review.googlesource.com/c/chromium/src/+/3430502 * [Extensions] Move some l10n file util methods to //extensions/browser https://chromium-review.googlesource.com/c/chromium/src/+/3408192 * chore: IWYU * Reland "webhid: Grant permissions for policy-allowed devices" https://chromium-review.googlesource.com/c/chromium/src/+/3444147 * Migrate base::Value::GetList() to base::Value::GetListDeprecated(): 2/N. https://chromium-review.googlesource.com/c/chromium/src/+/3435727 https://chromium-review.googlesource.com/c/chromium/src/+/3440910 https://chromium-review.googlesource.com/c/chromium/src/+/3440088 * [text blink period] Cache blink period instead of fetching from defaults https://chromium-review.googlesource.com/c/chromium/src/+/3419059 * chore: update picture-in-picture.patch https://chromium-review.googlesource.com/c/chromium/src/+/3252789 * ci: update to Xcode 13.2.1 https://chromium-review.googlesource.com/c/chromium/src/+/3437552 * chore: bump chromium in DEPS to 100.0.4882.1 * chore: update patches * chore: bump chromium in DEPS to 100.0.4884.0 * chore: update patches * chore: bump chromium in DEPS to 100.0.4886.0 * chore: update patches * Refactor DownloadManager to use StoragePartitionConfig https://chromium-review.googlesource.com/c/chromium/src/+/3222011 * Remove ToWebInputElement() in favor of new WebNode::DynamicTo<> helpers. https://chromium-review.googlesource.com/c/chromium/src/+/3433852 * refactor: autofill to use the color pipeline https://bugs.chromium.org/p/chromium/issues/detail?id=1249558 https://bugs.chromium.org/p/chromium/issues/detail?id=1003612 * [ProcessSingleton] Add many more trace events to cover all scenarios https://chromium-review.googlesource.com/c/chromium/src/+/3429325 * fixup! PIP20: add a new DocumentOverlayWindowViews subtype * chore: bump chromium in DEPS to 100.0.4888.0 * chore: update patches * chore: update picture-in-picture.patch * fixup! refactor: autofill to use the color pipeline * ci: fixup fix sync (cherry picked from commit c1e3e395465739bce5ca8e1c5ec1f5bd72b99ebd) * chore: bump chromium in DEPS to 100.0.4889.0 * chore: update patches * chore: fix feat_add_data_transfer_to_requestsingleinstancelock.patch * fixup! PIP20: add a new DocumentOverlayWindowViews subtype * Remove remaining NativeTheme::GetSystemColor() machinery. https://chromium-review.googlesource.com/c/chromium/src/+/3421719 * ci: fetch proper esbuild for macos * ci: fixup fetch proper esbuild for macos * fix: failing Node.js test on outdated CurrentValueSerializerFormatVersion * chore: bump chromium in DEPS to 100.0.4892.0 * 3460365: Set V8 fatal error callbacks during Isolate initialization https://chromium-review.googlesource.com/c/chromium/src/+/3460365 * 3454343: PIP20: use permanent top controls https://chromium-review.googlesource.com/c/chromium/src/+/3454343 * 3465574: Move most of GTK color mixers to ui/color/. https://chromium-review.googlesource.com/c/chromium/src/+/3465574 * chore: fixup patch indices * 3445327: [locales] Remove locales reference https://chromium-review.googlesource.com/c/chromium/src/+/3445327 * 3456548: [DBB][#7] Blue border falls back to all tab if cropped-to zero pixels https://chromium-review.googlesource.com/c/chromium/src/+/3456548 * 3441196: Convert GuestView's remaining legacy IPC messages to Mojo https://chromium-review.googlesource.com/c/chromium/src/+/3441196 * 3455491: Don't include run_loop.h in thread_task_runner_handle.h https://chromium-review.googlesource.com/c/chromium/src/+/3455491 * fixup! 3454343: PIP20: use permanent top controls * 3442501: Add missing includes of //base/observer_list.h https://chromium-review.googlesource.com/c/chromium/src/+/3442501 * 3437552: mac: Deploy a new hermetic build of Xcode 13.2.1 13C100 https://chromium-review.googlesource.com/c/chromium/src/+/3437552 * chore: bump chromium in DEPS to 100.0.4894.0 * fixup! 3460365: Set V8 fatal error callbacks during Isolate initialization * chore: update patches * 3425231: Use DnsOverHttpsConfig where appropriate https://chromium-review.googlesource.com/c/chromium/src/+/3425231 * test: disable test-heapsnapshot-near-heap-limit-worker.js As a result of CLs linked in https://bugs.chromium.org/p/v8/issues/detail?id=12503, heap snapshotting near the heap limit DCHECKS in Node.js specs. This will likely require a larger refactor in Node.js so i've disabled the test for now and opened an upstream issue on node-v8 issue at https://github.com/nodejs/node-v8/issues/218. * Port all usage of NativeTheme color IDs to color pipeline https://bugs.chromium.org/p/chromium/issues/detail?id=1249558 * chore: update patches after rebase * ci: use gen2 machine for more disk space * ci: don't try to make root volume writeable * ci: use older xcode/macos for tests * fix: html fullscreen transitions stacking (cherry picked from commit 5e10965cdd7b2a024def5fc568912cefd0f05b44) * ci: speed up woa testing (cherry picked from commit 75c33c48b032137794f5734348a9ee3daa60d9de) (cherry picked from commit e81996234029669663bf0daaababd34684dcbb17) * ci: disable flaky tests on WOA * ci: run remote tests separately to isolate issue there * tests: disable node test parallel/test-worker-debug for now * revert: fix: html fullscreen transitions stacking * tests: disable flaky test on macOS arm64 * fixup circleci config so build tools can find xcode version * make sure the workspace is clean before job runs (cherry picked from commit 75f713c9748ac1a356846c39f268886130554fd6) * tests: disable flaky test on Linux * ci: debug why windows i32 is crashing * Revert "ci: debug why windows i32 is crashing" This reverts commit 4c4bba87ea76f16ef3b304dadff59ad4d366f60f. Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: Jeremy Rose <nornagon@nornagon.net> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org> Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2022-02-25 18:17:35 +00:00
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = require('url').format({
pathname: `${fixturesPath}/pages/window-no-javascript.html`,
protocol: 'file',
slashes: true
2020-03-20 20:28:31 +00:00
});
w.webContents.executeJavaScript(`
{ b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
2020-03-20 20:28:31 +00:00
`);
const [, contents] = await emittedOnce(app, 'web-contents-created');
await emittedOnce(contents, 'did-finish-load');
// Click link on page
2020-03-20 20:28:31 +00:00
contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
const [, window] = await emittedOnce(app, 'browser-window-created');
const preferences = window.webContents.getLastWebPreferences();
2020-03-20 20:28:31 +00:00
expect(preferences.javascript).to.be.false();
});
it('defines a window.location getter', async () => {
2020-03-20 20:28:31 +00:00
let targetURL: string;
if (process.platform === 'win32') {
2020-03-20 20:28:31 +00:00
targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
} else {
2020-03-20 20:28:31 +00:00
targetURL = `file://${fixturesPath}/pages/base-page.html`;
}
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
2020-03-20 20:28:31 +00:00
w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
const [, window] = await emittedOnce(app, 'browser-window-created');
await emittedOnce(window.webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
});
it('defines a window.location setter', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
2020-03-20 20:28:31 +00:00
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
await emittedOnce(webContents, 'did-finish-load');
// When it loads, redirect
2020-03-20 20:28:31 +00:00
w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await emittedOnce(webContents, 'did-finish-load');
});
it('defines a window.location.href setter', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
2020-03-20 20:28:31 +00:00
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
await emittedOnce(webContents, 'did-finish-load');
// When it loads, redirect
2020-03-20 20:28:31 +00:00
w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await emittedOnce(webContents, 'did-finish-load');
});
it('open a blank page when no URL is specified', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(); null }');
const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
await emittedOnce(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('open a blank page when an empty URL is specified', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
await emittedOnce(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('does not throw an exception when the frameName is a built-in object property', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
const frameName = await new Promise((resolve) => {
w.webContents.setWindowOpenHandler(details => {
setImmediate(() => resolve(details.frameName));
return { action: 'allow' };
});
});
expect(frameName).to.equal('__proto__');
2020-03-20 20:28:31 +00:00
});
});
describe('window.opener', () => {
it('is null for main window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message');
expect(channel).to.equal('opener');
expect(opener).to.equal(null);
});
});
describe('navigator.mediaDevices', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
afterEach(() => {
2020-03-20 20:28:31 +00:00
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setPermissionRequestHandler(null);
2020-03-20 20:28:31 +00:00
});
it('can return labels of enumerated devices', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.true();
});
it('does not return labels of enumerated devices when permission denied', async () => {
2020-03-20 20:28:31 +00:00
session.defaultSession.setPermissionCheckHandler(() => false);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.false();
});
it('returns the same device ids across reloads', async () => {
2020-03-20 20:28:31 +00:00
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
});
it('can return new device id when cookie storage is cleared', async () => {
2020-03-20 20:28:31 +00:00
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
await ses.clearStorageData({ storages: ['cookies'] });
const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
});
it('provides a securityOrigin to the request handler', async () => {
session.defaultSession.setPermissionRequestHandler(
(wc, permission, callback, details) => {
if (details.securityOrigin !== undefined) {
callback(true);
} else {
callback(false);
}
}
);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
video: {
mandatory: {
chromeMediaSource: "desktop",
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
}).then((stream) => stream.getVideoTracks())`);
expect(labels.some((l: any) => l)).to.be.true();
});
2020-03-20 20:28:31 +00:00
});
describe('window.opener access', () => {
2020-03-20 20:28:31 +00:00
const scheme = 'app';
2020-03-20 20:28:31 +00:00
const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
const httpUrl1 = `${scheme}://origin1`;
const httpUrl2 = `${scheme}://origin2`;
const fileBlank = `file://${fixturesPath}/pages/blank.html`;
const httpBlank = `${scheme}://origin1/blank`;
const table = [
{ parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false },
{ parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false },
// {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open()
// {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open()
// NB. this is different from Chrome's behavior, which isolates file: urls from each other
{ parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true },
{ parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false }
2020-03-20 20:28:31 +00:00
];
const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
if (request.url.includes('blank')) {
2020-03-20 20:28:31 +00:00
callback(`${fixturesPath}/pages/blank.html`);
} else {
2020-03-20 20:28:31 +00:00
callback(`${fixturesPath}/pages/window-opener-location.html`);
}
2020-03-20 20:28:31 +00:00
});
});
after(() => {
protocol.unregisterProtocol(scheme);
2020-03-20 20:28:31 +00:00
});
afterEach(closeAllWindows);
describe('when opened from main window', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
for (const sandboxPopup of [false, true]) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
sandbox: sandboxPopup
}
}
}));
2020-03-20 20:28:31 +00:00
await w.loadURL(parent);
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
window.addEventListener('message', function f(e) {
resolve(e.data)
})
window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
2020-03-20 20:28:31 +00:00
})`);
if (openerAccessible) {
2020-03-20 20:28:31 +00:00
expect(childOpenerLocation).to.be.a('string');
} else {
2020-03-20 20:28:31 +00:00
expect(childOpenerLocation).to.be.null();
}
2020-03-20 20:28:31 +00:00
});
}
}
2020-03-20 20:28:31 +00:00
});
describe('when opened from <webview>', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
// This test involves three contexts:
// 1. The root BrowserWindow in which the test is run,
// 2. A <webview> belonging to the root window,
// 3. A window opened by calling window.open() from within the <webview>.
// We are testing whether context (3) can access context (2) under various conditions.
// This is context (1), the base window for the test.
const 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');
const parentCode = `new Promise((resolve) => {
// This is context (3), a child window of the WebView.
const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
window.addEventListener("message", e => {
resolve(e.data)
})
2020-03-20 20:28:31 +00:00
})`;
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
// This is context (2), a WebView which will call window.open()
const webview = new WebView()
2019-11-01 20:37:02 +00:00
webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
webview.setAttribute('webpreferences', 'contextIsolation=no')
webview.setAttribute('allowpopups', 'on')
webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
webview.addEventListener('dom-ready', async () => {
webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
})
document.body.appendChild(webview)
2020-03-20 20:28:31 +00:00
})`);
if (openerAccessible) {
2020-03-20 20:28:31 +00:00
expect(childOpenerLocation).to.be.a('string');
} else {
2020-03-20 20:28:31 +00:00
expect(childOpenerLocation).to.be.null();
}
2020-03-20 20:28:31 +00:00
});
}
2020-03-20 20:28:31 +00:00
});
});
describe('storage', () => {
describe('custom non standard schemes', () => {
2020-03-20 20:28:31 +00:00
const protocolName = 'storage';
let contents: WebContents;
before(() => {
protocol.registerFileProtocol(protocolName, (request, callback) => {
2020-03-20 20:28:31 +00:00
const parsedUrl = url.parse(request.url);
let filename;
switch (parsedUrl.pathname) {
2020-03-20 20:28:31 +00:00
case '/localStorage' : filename = 'local_storage.html'; break;
case '/sessionStorage' : filename = 'session_storage.html'; break;
case '/WebSQL' : filename = 'web_sql.html'; break;
case '/indexedDB' : filename = 'indexed_db.html'; break;
case '/cookie' : filename = 'cookie.html'; break;
default : filename = '';
}
2020-03-20 20:28:31 +00:00
callback({ path: `${fixturesPath}/pages/storage/${filename}` });
});
2020-03-20 20:28:31 +00:00
});
after(() => {
protocol.unregisterProtocol(protocolName);
2020-03-20 20:28:31 +00:00
});
beforeEach(() => {
contents = (webContents as any).create({
nodeIntegration: true,
contextIsolation: false
2020-03-20 20:28:31 +00:00
});
});
afterEach(() => {
2020-03-20 20:28:31 +00:00
(contents as any).destroy();
contents = null as any;
});
it('cannot access localStorage', async () => {
const response = emittedOnce(ipcMain, 'local-storage-response');
2020-03-20 20:28:31 +00:00
contents.loadURL(protocolName + '://host/localStorage');
const [, error] = await response;
expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
2020-03-20 20:28:31 +00:00
});
it('cannot access sessionStorage', async () => {
const response = emittedOnce(ipcMain, 'session-storage-response');
2020-03-20 20:28:31 +00:00
contents.loadURL(`${protocolName}://host/sessionStorage`);
const [, error] = await response;
expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
2020-03-20 20:28:31 +00:00
});
it('cannot access WebSQL database', async () => {
const response = emittedOnce(ipcMain, 'web-sql-response');
2020-03-20 20:28:31 +00:00
contents.loadURL(`${protocolName}://host/WebSQL`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
2020-03-20 20:28:31 +00:00
});
it('cannot access indexedDB', async () => {
const response = emittedOnce(ipcMain, 'indexed-db-response');
2020-03-20 20:28:31 +00:00
contents.loadURL(`${protocolName}://host/indexedDB`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
2020-03-20 20:28:31 +00:00
});
it('cannot access cookie', async () => {
const response = emittedOnce(ipcMain, 'cookie-response');
2020-03-20 20:28:31 +00:00
contents.loadURL(`${protocolName}://host/cookie`);
const [, error] = await response;
expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
2020-03-20 20:28:31 +00:00
});
});
describe('can be accessed', () => {
2020-03-20 20:28:31 +00:00
let server: http.Server;
let serverUrl: string;
let serverCrossSiteUrl: string;
before((done) => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
2020-03-20 20:28:31 +00:00
res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
2020-03-20 20:28:31 +00:00
res.end('<html><script>window.localStorage</script></html>');
} else {
2020-03-20 20:28:31 +00:00
res.end();
}
2020-03-20 20:28:31 +00:00
};
setTimeout(respond, 0);
});
server.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}`;
serverCrossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`;
done();
});
});
after(() => {
2020-03-20 20:28:31 +00:00
server.close();
server = null as any;
});
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
it(testTitle, async () => {
const w = new BrowserWindow({
show: false,
...extraPreferences
2020-03-20 20:28:31 +00:00
});
let redirected = false;
w.webContents.on('crashed', () => {
2020-03-20 20:28:31 +00:00
expect.fail('renderer crashed / was killed');
});
w.webContents.on('did-redirect-navigation', (event, url) => {
2020-03-20 20:28:31 +00:00
expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
redirected = true;
});
await w.loadURL(`${serverUrl}/redirect-cross-site`);
expect(redirected).to.be.true('didnt redirect');
2020-03-20 20:28:31 +00:00
});
};
testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
});
describe('enableWebSQL webpreference', () => {
const origin = `${standardScheme}://fake-host`;
const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
const sqlPartition = 'web-sql-preference-test';
const sqlSession = session.fromPartition(sqlPartition);
const securityError = 'An attempt was made to break through the security policy of the user agent.';
let contents: WebContents, w: BrowserWindow;
before(() => {
sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
callback({ path: filePath });
});
});
after(() => {
sqlSession.protocol.unregisterProtocol(standardScheme);
});
afterEach(async () => {
if (contents) {
(contents as any).destroy();
contents = null as any;
}
await closeAllWindows();
(w as any) = null;
});
it('default value allows websql', async () => {
contents = (webContents as any).create({
session: sqlSession,
nodeIntegration: true,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
expect(error).to.be.null();
});
it('when set to false can disallow websql', async () => {
contents = (webContents as any).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
});
it('when set to false does not disable indexedDB', async () => {
contents = (webContents as any).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
const dbName = 'random';
const result = await contents.executeJavaScript(`
new Promise((resolve, reject) => {
try {
let req = window.indexedDB.open('${dbName}');
req.onsuccess = (event) => {
let db = req.result;
resolve(db.name);
}
req.onerror = (event) => { resolve(event.target.code); }
} catch (e) {
resolve(e.message);
}
});
`);
expect(result).to.equal(dbName);
});
it('child webContents can override when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents cannot override when the embedder has disallowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableWebSQL: false,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL('data:text/html,<html></html>');
const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents can use websql when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.be.null();
});
});
2020-03-20 20:28:31 +00:00
});
ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
const pdfSource = url.format({
2020-02-13 00:39:12 +00:00
pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
protocol: 'file',
slashes: true
2020-03-20 20:28:31 +00:00
});
it('successfully loads a PDF file', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
await emittedOnce(w.webContents, 'did-finish-load');
});
2020-02-13 00:39:12 +00:00
it('opens when loading a pdf resource as top level navigation', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
const [, contents] = await emittedOnce(app, 'web-contents-created');
await emittedOnce(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
2020-03-20 20:28:31 +00:00
});
2020-02-13 00:39:12 +00:00
it('opens when loading a pdf resource in a iframe', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
const [, contents] = await emittedOnce(app, 'web-contents-created');
await emittedOnce(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
2020-03-20 20:28:31 +00:00
});
});
describe('window.history', () => {
describe('window.history.pushState', () => {
it('should push state after calling history.pushState() from the same url', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// History should have current page by now.
2020-03-20 20:28:31 +00:00
expect((w.webContents as any).length()).to.equal(1);
2020-03-20 20:28:31 +00:00
const waitCommit = emittedOnce(w.webContents, 'navigation-entry-committed');
w.webContents.executeJavaScript('window.history.pushState({}, "")');
await waitCommit;
// Initial page + pushed state.
2020-03-20 20:28:31 +00:00
expect((w.webContents as any).length()).to.equal(2);
});
});
});
describe('chrome://media-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://media-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('chrome://webrtc-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://webrtc-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('document.hasFocus', () => {
it('has correct value when multiple windows are opened', async () => {
const w1 = new BrowserWindow({ show: true });
const w2 = new BrowserWindow({ show: true });
const w3 = new BrowserWindow({ show: false });
await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents().id).to.equal(w2.webContents.id);
let focus = false;
focus = await w1.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
focus = await w2.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.true();
focus = await w3.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
});
});
describe('navigator.userAgentData', () => {
// These tests are done on an http server because navigator.userAgentData
// requires a secure context.
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
serverUrl = `http://localhost:${(server.address() as any).port}`;
});
after(() => {
server.close();
});
describe('is not empty', () => {
it('by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a session-wide UA override', async () => {
const ses = session.fromPartition(`${Math.random()}`);
ses.setUserAgent('foobar');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setUserAgent('foo');
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override at load time', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl, {
userAgent: 'foo'
});
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
});
describe('brand list', () => {
it('contains chromium', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
expect(brands.map((b: any) => b.brand)).to.include('Chromium');
});
});
});
2020-03-20 20:28:31 +00:00
});
describe('font fallback', () => {
async function getRenderedFonts (html: string) {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
try {
2020-03-20 20:28:31 +00:00
await w.loadURL(`data:text/html,${html}`);
w.webContents.debugger.attach();
const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
await sendCommand('CSS.enable');
const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
return fonts;
} finally {
2020-03-20 20:28:31 +00:00
w.close();
}
}
it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
2020-03-20 20:28:31 +00:00
const html = '<body style="font-family: sans-serif">test</body>';
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') {
expect(fonts[0].familyName).to.equal('Arial');
} else if (process.platform === 'darwin') {
expect(fonts[0].familyName).to.equal('Helvetica');
} else if (process.platform === 'linux') {
expect(fonts[0].familyName).to.equal('DejaVu Sans');
} // I think this depends on the distro? We don't specify a default.
2020-03-20 20:28:31 +00:00
});
ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
const html = `
<html lang="ja-JP">
<head>
<meta charset="utf-8" />
</head>
<body style="font-family: sans-serif">test </body>
</html>
2020-03-20 20:28:31 +00:00
`;
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); }
});
});
describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
const fullscreenChildHtml = promisify(fs.readFile)(
path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
2020-03-20 20:28:31 +00:00
);
let w: BrowserWindow, server: http.Server;
before(() => {
server = http.createServer(async (_req, res) => {
2020-03-20 20:28:31 +00:00
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(await fullscreenChildHtml);
res.end();
});
2020-03-20 20:28:31 +00:00
server.listen(8989, '127.0.0.1');
});
beforeEach(() => {
w = new BrowserWindow({
show: true,
fullscreen: true,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
2020-03-20 20:28:31 +00:00
});
});
afterEach(async () => {
await closeAllWindows();
(w as any) = null;
2020-03-20 20:28:31 +00:00
server.close();
});
ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
const html =
'<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await delay(500);
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
2020-03-20 20:28:31 +00:00
});
ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
await emittedOnce(w, 'enter-full-screen');
const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
const html =
'<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await emittedOnce(w.webContents, 'leave-html-full-screen');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
w.setFullScreen(false);
await emittedOnce(w, 'leave-full-screen');
});
chore: bump chromium to 100.0.4894.0 (main) (#32852) * chore: bump chromium in DEPS to 100.0.4880.0 * resolve conflicts * chore: update patches * fix patch * PIP20: add a new DocumentOverlayWindowViews subtype https://chromium-review.googlesource.com/c/chromium/src/+/3252789 * Clean up PictureInPictureWindowManager::EnterPictureInPicture() https://chromium-review.googlesource.com/c/chromium/src/+/3424145 * Remove StoragePartitionId. https://chromium-review.googlesource.com/c/chromium/src/+/2811120 * Remove FLoC code https://chromium-review.googlesource.com/c/chromium/src/+/3424359 * media: Make AddSupportedKeySystems() Async https://chromium-review.googlesource.com/c/chromium/src/+/3430502 * [Extensions] Move some l10n file util methods to //extensions/browser https://chromium-review.googlesource.com/c/chromium/src/+/3408192 * chore: IWYU * Reland "webhid: Grant permissions for policy-allowed devices" https://chromium-review.googlesource.com/c/chromium/src/+/3444147 * Migrate base::Value::GetList() to base::Value::GetListDeprecated(): 2/N. https://chromium-review.googlesource.com/c/chromium/src/+/3435727 https://chromium-review.googlesource.com/c/chromium/src/+/3440910 https://chromium-review.googlesource.com/c/chromium/src/+/3440088 * [text blink period] Cache blink period instead of fetching from defaults https://chromium-review.googlesource.com/c/chromium/src/+/3419059 * chore: update picture-in-picture.patch https://chromium-review.googlesource.com/c/chromium/src/+/3252789 * ci: update to Xcode 13.2.1 https://chromium-review.googlesource.com/c/chromium/src/+/3437552 * chore: bump chromium in DEPS to 100.0.4882.1 * chore: update patches * chore: bump chromium in DEPS to 100.0.4884.0 * chore: update patches * chore: bump chromium in DEPS to 100.0.4886.0 * chore: update patches * Refactor DownloadManager to use StoragePartitionConfig https://chromium-review.googlesource.com/c/chromium/src/+/3222011 * Remove ToWebInputElement() in favor of new WebNode::DynamicTo<> helpers. https://chromium-review.googlesource.com/c/chromium/src/+/3433852 * refactor: autofill to use the color pipeline https://bugs.chromium.org/p/chromium/issues/detail?id=1249558 https://bugs.chromium.org/p/chromium/issues/detail?id=1003612 * [ProcessSingleton] Add many more trace events to cover all scenarios https://chromium-review.googlesource.com/c/chromium/src/+/3429325 * fixup! PIP20: add a new DocumentOverlayWindowViews subtype * chore: bump chromium in DEPS to 100.0.4888.0 * chore: update patches * chore: update picture-in-picture.patch * fixup! refactor: autofill to use the color pipeline * ci: fixup fix sync (cherry picked from commit c1e3e395465739bce5ca8e1c5ec1f5bd72b99ebd) * chore: bump chromium in DEPS to 100.0.4889.0 * chore: update patches * chore: fix feat_add_data_transfer_to_requestsingleinstancelock.patch * fixup! PIP20: add a new DocumentOverlayWindowViews subtype * Remove remaining NativeTheme::GetSystemColor() machinery. https://chromium-review.googlesource.com/c/chromium/src/+/3421719 * ci: fetch proper esbuild for macos * ci: fixup fetch proper esbuild for macos * fix: failing Node.js test on outdated CurrentValueSerializerFormatVersion * chore: bump chromium in DEPS to 100.0.4892.0 * 3460365: Set V8 fatal error callbacks during Isolate initialization https://chromium-review.googlesource.com/c/chromium/src/+/3460365 * 3454343: PIP20: use permanent top controls https://chromium-review.googlesource.com/c/chromium/src/+/3454343 * 3465574: Move most of GTK color mixers to ui/color/. https://chromium-review.googlesource.com/c/chromium/src/+/3465574 * chore: fixup patch indices * 3445327: [locales] Remove locales reference https://chromium-review.googlesource.com/c/chromium/src/+/3445327 * 3456548: [DBB][#7] Blue border falls back to all tab if cropped-to zero pixels https://chromium-review.googlesource.com/c/chromium/src/+/3456548 * 3441196: Convert GuestView's remaining legacy IPC messages to Mojo https://chromium-review.googlesource.com/c/chromium/src/+/3441196 * 3455491: Don't include run_loop.h in thread_task_runner_handle.h https://chromium-review.googlesource.com/c/chromium/src/+/3455491 * fixup! 3454343: PIP20: use permanent top controls * 3442501: Add missing includes of //base/observer_list.h https://chromium-review.googlesource.com/c/chromium/src/+/3442501 * 3437552: mac: Deploy a new hermetic build of Xcode 13.2.1 13C100 https://chromium-review.googlesource.com/c/chromium/src/+/3437552 * chore: bump chromium in DEPS to 100.0.4894.0 * fixup! 3460365: Set V8 fatal error callbacks during Isolate initialization * chore: update patches * 3425231: Use DnsOverHttpsConfig where appropriate https://chromium-review.googlesource.com/c/chromium/src/+/3425231 * test: disable test-heapsnapshot-near-heap-limit-worker.js As a result of CLs linked in https://bugs.chromium.org/p/v8/issues/detail?id=12503, heap snapshotting near the heap limit DCHECKS in Node.js specs. This will likely require a larger refactor in Node.js so i've disabled the test for now and opened an upstream issue on node-v8 issue at https://github.com/nodejs/node-v8/issues/218. * Port all usage of NativeTheme color IDs to color pipeline https://bugs.chromium.org/p/chromium/issues/detail?id=1249558 * chore: update patches after rebase * ci: use gen2 machine for more disk space * ci: don't try to make root volume writeable * ci: use older xcode/macos for tests * fix: html fullscreen transitions stacking (cherry picked from commit 5e10965cdd7b2a024def5fc568912cefd0f05b44) * ci: speed up woa testing (cherry picked from commit 75c33c48b032137794f5734348a9ee3daa60d9de) (cherry picked from commit e81996234029669663bf0daaababd34684dcbb17) * ci: disable flaky tests on WOA * ci: run remote tests separately to isolate issue there * tests: disable node test parallel/test-worker-debug for now * revert: fix: html fullscreen transitions stacking * tests: disable flaky test on macOS arm64 * fixup circleci config so build tools can find xcode version * make sure the workspace is clean before job runs (cherry picked from commit 75f713c9748ac1a356846c39f268886130554fd6) * tests: disable flaky test on Linux * ci: debug why windows i32 is crashing * Revert "ci: debug why windows i32 is crashing" This reverts commit 4c4bba87ea76f16ef3b304dadff59ad4d366f60f. Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: Jeremy Rose <nornagon@nornagon.net> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org> Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2022-02-25 18:17:35 +00:00
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
if (process.platform === 'darwin') await emittedOnce(w, 'enter-full-screen');
const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.true();
2020-03-20 20:28:31 +00:00
await w.webContents.executeJavaScript('document.exitFullscreen()');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
2020-03-20 20:28:31 +00:00
});
});
describe('navigator.serial', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const getPorts: any = () => {
return w.webContents.executeJavaScript(`
navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.removeAllListeners('select-serial-port');
});
it('does not return a port if select-serial-port event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const port = await getPorts();
expect(port).to.equal('NotFoundError: No port selected by the user.');
});
it('does not return a port when permission denied', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback(portList[0].portId);
});
session.defaultSession.setPermissionCheckHandler(() => false);
const port = await getPorts();
expect(port).to.equal('NotFoundError: No port selected by the user.');
});
it('does not crash when select-serial-port is called with an invalid port', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback('i-do-not-exist');
});
const port = await getPorts();
expect(port).to.equal('NotFoundError: No port selected by the user.');
});
it('returns a port when select-serial-port event is defined', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
const port = await getPorts();
if (havePorts) {
expect(port).to.equal('[object SerialPort]');
} else {
expect(port).to.equal('NotFoundError: No port selected by the user.');
}
});
it('navigator.serial.getPorts() returns values', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts).to.not.be.empty();
}
});
});
describe('navigator.clipboard', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
webPreferences: {
enableBlinkFeatures: 'Serial'
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const readClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.equal('Read permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
});
ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
let w: BrowserWindow;
const expectedBadgeCount = 42;
const fireAppBadgeAction: any = (action: string, value: any) => {
return w.webContents.executeJavaScript(`
navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
};
// For some reason on macOS changing the badge count doesn't happen right away, so wait
// until it changes.
async function waitForBadgeCount (value: number) {
let badgeCount = app.getBadgeCount();
while (badgeCount !== value) {
await new Promise(resolve => setTimeout(resolve, 10));
badgeCount = app.getBadgeCount();
}
return badgeCount;
}
describe('in the renderer', () => {
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can set a numerical value', async () => {
const result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
});
it('setAppBadge can set an empty(dot) value', async () => {
const result = await fireAppBadgeAction('set');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
it('clearAppBadge can clear a value', async () => {
let result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
result = await fireAppBadgeAction('clear');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
});
describe('in a service worker', () => {
beforeEach(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
});
afterEach(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
});
it('clearAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'setAppBadge') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS clearing app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
});
});
});
describe('navigator.bluetooth', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
enableBlinkFeatures: 'WebBluetooth'
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
it('can request bluetooth devices', async () => {
const bluetooth = await w.webContents.executeJavaScript(`
navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
});
});
feat: add support for WebHID (#30213) * feat: add support for WebHID * Apply suggestions from code review Co-authored-by: Jeremy Rose <jeremya@chromium.org> * Address review feedback * Address review feedback * chore: clear granted_devices on navigation Also added test to verify devices get cleared * fixup testing for device clear * make sure navigator.hid.getDevices is run on correct frame * clear granted devices on RenderFrameHost deletion/change * manage device permissions per RenderFrameHost This change makes sure we don't clear device permission prematurely due to child frame navigation * Update shell/browser/api/electron_api_web_contents.cc Co-authored-by: Jeremy Rose <jeremya@chromium.org> * apply review feedback from @zcbenz * Match upstream ObjectMap This change matches what ObjectPermissionContextBase uses to cache object permissions: https://source.chromium.org/chromium/chromium/src/+/main:components/permissions/object_permission_context_base.h;l=52;drc=8f95b5eab2797a3e26bba299f3b0df85bfc98bf5;bpv=1;bpt=0 The main reason for this was to resolve this crash on Win x64: ok 2 WebContentsView doesn't crash when GCed during allocation Received fatal exception EXCEPTION_ACCESS_VIOLATION Backtrace: gin::WrappableBase::SecondWeakCallback [0x00007FF6F2AFA005+133] (o:\gin\wrappable.cc:53) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacks [0x00007FF6F028F9AB+171] (o:\v8\src\handles\global-handles.cc:1400) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacksFromTask [0x00007FF6F028F867+391] (o:\v8\src\handles\global-handles.cc:1387) node::PerIsolatePlatformData::RunForegroundTask [0x00007FF6F3B4D065+317] (o:\third_party\electron_node\src\node_platform.cc:415) node::PerIsolatePlatformData::FlushForegroundTasksInternal [0x00007FF6F3B4C424+776] (o:\third_party\electron_node\src\node_platform.cc:479) uv_run [0x00007FF6F2DDD07C+492] (o:\third_party\electron_node\deps\uv\src\win\core.c:609) electron::NodeBindings::UvRunOnce [0x00007FF6EEE1E036+294] (o:\electron\shell\common\node_bindings.cc:631) base::TaskAnnotator::RunTask [0x00007FF6F2318A19+457] (o:\base\task\common\task_annotator.cc:178) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl [0x00007FF6F2E6F553+963] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:361) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork [0x00007FF6F2E6EC69+137] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:266) base::MessagePumpForUI::DoRunLoop [0x00007FF6F235AA58+216] (o:\base\message_loop\message_pump_win.cc:221) base::MessagePumpWin::Run [0x00007FF6F235A01A+106] (o:\base\message_loop\message_pump_win.cc:79) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run [0x00007FF6F2E702DA+682] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:470) base::RunLoop::Run [0x00007FF6F22F95BA+842] (o:\base\run_loop.cc:136) content::BrowserMainLoop::RunMainMessageLoop [0x00007FF6F14423CC+208] (o:\content\browser\browser_main_loop.cc:990) content::BrowserMainRunnerImpl::Run [0x00007FF6F144402F+143] (o:\content\browser\browser_main_runner_impl.cc:153) content::BrowserMain [0x00007FF6F143F911+257] (o:\content\browser\browser_main.cc:49) content::RunBrowserProcessMain [0x00007FF6EFFA7D18+112] (o:\content\app\content_main_runner_impl.cc:608) content::ContentMainRunnerImpl::RunBrowser [0x00007FF6EFFA8CF4+1220] (o:\content\app\content_main_runner_impl.cc:1104) content::ContentMainRunnerImpl::Run [0x00007FF6EFFA87C9+393] (o:\content\app\content_main_runner_impl.cc:971) content::RunContentProcess [0x00007FF6EFFA73BD+733] (o:\content\app\content_main.cc:394) content::ContentMain [0x00007FF6EFFA79E1+54] (o:\content\app\content_main.cc:422) wWinMain [0x00007FF6EECA1535+889] (o:\electron\shell\app\electron_main.cc:291) __scrt_common_main_seh [0x00007FF6F6F88482+262] (d:\A01\_work\6\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288) BaseThreadInitThunk [0x00007FFEC0087034+20] RtlUserThreadStart [0x00007FFEC1F02651+33] ✗ Electron tests failed with code 0xc0000005. Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2021-09-23 11:00:11 +00:00
describe('navigator.hid', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
serverUrl = `http://localhost:${(server.address() as any).port}`;
});
const requestDevices: any = () => {
feat: add support for WebHID (#30213) * feat: add support for WebHID * Apply suggestions from code review Co-authored-by: Jeremy Rose <jeremya@chromium.org> * Address review feedback * Address review feedback * chore: clear granted_devices on navigation Also added test to verify devices get cleared * fixup testing for device clear * make sure navigator.hid.getDevices is run on correct frame * clear granted devices on RenderFrameHost deletion/change * manage device permissions per RenderFrameHost This change makes sure we don't clear device permission prematurely due to child frame navigation * Update shell/browser/api/electron_api_web_contents.cc Co-authored-by: Jeremy Rose <jeremya@chromium.org> * apply review feedback from @zcbenz * Match upstream ObjectMap This change matches what ObjectPermissionContextBase uses to cache object permissions: https://source.chromium.org/chromium/chromium/src/+/main:components/permissions/object_permission_context_base.h;l=52;drc=8f95b5eab2797a3e26bba299f3b0df85bfc98bf5;bpv=1;bpt=0 The main reason for this was to resolve this crash on Win x64: ok 2 WebContentsView doesn't crash when GCed during allocation Received fatal exception EXCEPTION_ACCESS_VIOLATION Backtrace: gin::WrappableBase::SecondWeakCallback [0x00007FF6F2AFA005+133] (o:\gin\wrappable.cc:53) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacks [0x00007FF6F028F9AB+171] (o:\v8\src\handles\global-handles.cc:1400) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacksFromTask [0x00007FF6F028F867+391] (o:\v8\src\handles\global-handles.cc:1387) node::PerIsolatePlatformData::RunForegroundTask [0x00007FF6F3B4D065+317] (o:\third_party\electron_node\src\node_platform.cc:415) node::PerIsolatePlatformData::FlushForegroundTasksInternal [0x00007FF6F3B4C424+776] (o:\third_party\electron_node\src\node_platform.cc:479) uv_run [0x00007FF6F2DDD07C+492] (o:\third_party\electron_node\deps\uv\src\win\core.c:609) electron::NodeBindings::UvRunOnce [0x00007FF6EEE1E036+294] (o:\electron\shell\common\node_bindings.cc:631) base::TaskAnnotator::RunTask [0x00007FF6F2318A19+457] (o:\base\task\common\task_annotator.cc:178) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl [0x00007FF6F2E6F553+963] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:361) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork [0x00007FF6F2E6EC69+137] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:266) base::MessagePumpForUI::DoRunLoop [0x00007FF6F235AA58+216] (o:\base\message_loop\message_pump_win.cc:221) base::MessagePumpWin::Run [0x00007FF6F235A01A+106] (o:\base\message_loop\message_pump_win.cc:79) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run [0x00007FF6F2E702DA+682] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:470) base::RunLoop::Run [0x00007FF6F22F95BA+842] (o:\base\run_loop.cc:136) content::BrowserMainLoop::RunMainMessageLoop [0x00007FF6F14423CC+208] (o:\content\browser\browser_main_loop.cc:990) content::BrowserMainRunnerImpl::Run [0x00007FF6F144402F+143] (o:\content\browser\browser_main_runner_impl.cc:153) content::BrowserMain [0x00007FF6F143F911+257] (o:\content\browser\browser_main.cc:49) content::RunBrowserProcessMain [0x00007FF6EFFA7D18+112] (o:\content\app\content_main_runner_impl.cc:608) content::ContentMainRunnerImpl::RunBrowser [0x00007FF6EFFA8CF4+1220] (o:\content\app\content_main_runner_impl.cc:1104) content::ContentMainRunnerImpl::Run [0x00007FF6EFFA87C9+393] (o:\content\app\content_main_runner_impl.cc:971) content::RunContentProcess [0x00007FF6EFFA73BD+733] (o:\content\app\content_main.cc:394) content::ContentMain [0x00007FF6EFFA79E1+54] (o:\content\app\content_main.cc:422) wWinMain [0x00007FF6EECA1535+889] (o:\electron\shell\app\electron_main.cc:291) __scrt_common_main_seh [0x00007FF6F6F88482+262] (d:\A01\_work\6\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288) BaseThreadInitThunk [0x00007FFEC0087034+20] RtlUserThreadStart [0x00007FFEC1F02651+33] ✗ Electron tests failed with code 0xc0000005. Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2021-09-23 11:00:11 +00:00
return w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-hid-device');
});
it('does not return a device if select-hid-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
feat: add support for WebHID (#30213) * feat: add support for WebHID * Apply suggestions from code review Co-authored-by: Jeremy Rose <jeremya@chromium.org> * Address review feedback * Address review feedback * chore: clear granted_devices on navigation Also added test to verify devices get cleared * fixup testing for device clear * make sure navigator.hid.getDevices is run on correct frame * clear granted devices on RenderFrameHost deletion/change * manage device permissions per RenderFrameHost This change makes sure we don't clear device permission prematurely due to child frame navigation * Update shell/browser/api/electron_api_web_contents.cc Co-authored-by: Jeremy Rose <jeremya@chromium.org> * apply review feedback from @zcbenz * Match upstream ObjectMap This change matches what ObjectPermissionContextBase uses to cache object permissions: https://source.chromium.org/chromium/chromium/src/+/main:components/permissions/object_permission_context_base.h;l=52;drc=8f95b5eab2797a3e26bba299f3b0df85bfc98bf5;bpv=1;bpt=0 The main reason for this was to resolve this crash on Win x64: ok 2 WebContentsView doesn't crash when GCed during allocation Received fatal exception EXCEPTION_ACCESS_VIOLATION Backtrace: gin::WrappableBase::SecondWeakCallback [0x00007FF6F2AFA005+133] (o:\gin\wrappable.cc:53) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacks [0x00007FF6F028F9AB+171] (o:\v8\src\handles\global-handles.cc:1400) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacksFromTask [0x00007FF6F028F867+391] (o:\v8\src\handles\global-handles.cc:1387) node::PerIsolatePlatformData::RunForegroundTask [0x00007FF6F3B4D065+317] (o:\third_party\electron_node\src\node_platform.cc:415) node::PerIsolatePlatformData::FlushForegroundTasksInternal [0x00007FF6F3B4C424+776] (o:\third_party\electron_node\src\node_platform.cc:479) uv_run [0x00007FF6F2DDD07C+492] (o:\third_party\electron_node\deps\uv\src\win\core.c:609) electron::NodeBindings::UvRunOnce [0x00007FF6EEE1E036+294] (o:\electron\shell\common\node_bindings.cc:631) base::TaskAnnotator::RunTask [0x00007FF6F2318A19+457] (o:\base\task\common\task_annotator.cc:178) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl [0x00007FF6F2E6F553+963] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:361) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork [0x00007FF6F2E6EC69+137] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:266) base::MessagePumpForUI::DoRunLoop [0x00007FF6F235AA58+216] (o:\base\message_loop\message_pump_win.cc:221) base::MessagePumpWin::Run [0x00007FF6F235A01A+106] (o:\base\message_loop\message_pump_win.cc:79) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run [0x00007FF6F2E702DA+682] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:470) base::RunLoop::Run [0x00007FF6F22F95BA+842] (o:\base\run_loop.cc:136) content::BrowserMainLoop::RunMainMessageLoop [0x00007FF6F14423CC+208] (o:\content\browser\browser_main_loop.cc:990) content::BrowserMainRunnerImpl::Run [0x00007FF6F144402F+143] (o:\content\browser\browser_main_runner_impl.cc:153) content::BrowserMain [0x00007FF6F143F911+257] (o:\content\browser\browser_main.cc:49) content::RunBrowserProcessMain [0x00007FF6EFFA7D18+112] (o:\content\app\content_main_runner_impl.cc:608) content::ContentMainRunnerImpl::RunBrowser [0x00007FF6EFFA8CF4+1220] (o:\content\app\content_main_runner_impl.cc:1104) content::ContentMainRunnerImpl::Run [0x00007FF6EFFA87C9+393] (o:\content\app\content_main_runner_impl.cc:971) content::RunContentProcess [0x00007FF6EFFA73BD+733] (o:\content\app\content_main.cc:394) content::ContentMain [0x00007FF6EFFA79E1+54] (o:\content\app\content_main.cc:422) wWinMain [0x00007FF6EECA1535+889] (o:\electron\shell\app\electron_main.cc:291) __scrt_common_main_seh [0x00007FF6F6F88482+262] (d:\A01\_work\6\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288) BaseThreadInitThunk [0x00007FFEC0087034+20] RtlUserThreadStart [0x00007FFEC1F02651+33] ✗ Electron tests failed with code 0xc0000005. Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2021-09-23 11:00:11 +00:00
expect(device).to.equal('');
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
feat: add support for WebHID (#30213) * feat: add support for WebHID * Apply suggestions from code review Co-authored-by: Jeremy Rose <jeremya@chromium.org> * Address review feedback * Address review feedback * chore: clear granted_devices on navigation Also added test to verify devices get cleared * fixup testing for device clear * make sure navigator.hid.getDevices is run on correct frame * clear granted devices on RenderFrameHost deletion/change * manage device permissions per RenderFrameHost This change makes sure we don't clear device permission prematurely due to child frame navigation * Update shell/browser/api/electron_api_web_contents.cc Co-authored-by: Jeremy Rose <jeremya@chromium.org> * apply review feedback from @zcbenz * Match upstream ObjectMap This change matches what ObjectPermissionContextBase uses to cache object permissions: https://source.chromium.org/chromium/chromium/src/+/main:components/permissions/object_permission_context_base.h;l=52;drc=8f95b5eab2797a3e26bba299f3b0df85bfc98bf5;bpv=1;bpt=0 The main reason for this was to resolve this crash on Win x64: ok 2 WebContentsView doesn't crash when GCed during allocation Received fatal exception EXCEPTION_ACCESS_VIOLATION Backtrace: gin::WrappableBase::SecondWeakCallback [0x00007FF6F2AFA005+133] (o:\gin\wrappable.cc:53) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacks [0x00007FF6F028F9AB+171] (o:\v8\src\handles\global-handles.cc:1400) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacksFromTask [0x00007FF6F028F867+391] (o:\v8\src\handles\global-handles.cc:1387) node::PerIsolatePlatformData::RunForegroundTask [0x00007FF6F3B4D065+317] (o:\third_party\electron_node\src\node_platform.cc:415) node::PerIsolatePlatformData::FlushForegroundTasksInternal [0x00007FF6F3B4C424+776] (o:\third_party\electron_node\src\node_platform.cc:479) uv_run [0x00007FF6F2DDD07C+492] (o:\third_party\electron_node\deps\uv\src\win\core.c:609) electron::NodeBindings::UvRunOnce [0x00007FF6EEE1E036+294] (o:\electron\shell\common\node_bindings.cc:631) base::TaskAnnotator::RunTask [0x00007FF6F2318A19+457] (o:\base\task\common\task_annotator.cc:178) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl [0x00007FF6F2E6F553+963] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:361) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork [0x00007FF6F2E6EC69+137] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:266) base::MessagePumpForUI::DoRunLoop [0x00007FF6F235AA58+216] (o:\base\message_loop\message_pump_win.cc:221) base::MessagePumpWin::Run [0x00007FF6F235A01A+106] (o:\base\message_loop\message_pump_win.cc:79) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run [0x00007FF6F2E702DA+682] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:470) base::RunLoop::Run [0x00007FF6F22F95BA+842] (o:\base\run_loop.cc:136) content::BrowserMainLoop::RunMainMessageLoop [0x00007FF6F14423CC+208] (o:\content\browser\browser_main_loop.cc:990) content::BrowserMainRunnerImpl::Run [0x00007FF6F144402F+143] (o:\content\browser\browser_main_runner_impl.cc:153) content::BrowserMain [0x00007FF6F143F911+257] (o:\content\browser\browser_main.cc:49) content::RunBrowserProcessMain [0x00007FF6EFFA7D18+112] (o:\content\app\content_main_runner_impl.cc:608) content::ContentMainRunnerImpl::RunBrowser [0x00007FF6EFFA8CF4+1220] (o:\content\app\content_main_runner_impl.cc:1104) content::ContentMainRunnerImpl::Run [0x00007FF6EFFA87C9+393] (o:\content\app\content_main_runner_impl.cc:971) content::RunContentProcess [0x00007FF6EFFA73BD+733] (o:\content\app\content_main.cc:394) content::ContentMain [0x00007FF6EFFA79E1+54] (o:\content\app\content_main.cc:422) wWinMain [0x00007FF6EECA1535+889] (o:\electron\shell\app\electron_main.cc:291) __scrt_common_main_seh [0x00007FF6F6F88482+262] (d:\A01\_work\6\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288) BaseThreadInitThunk [0x00007FFEC0087034+20] RtlUserThreadStart [0x00007FFEC1F02651+33] ✗ Electron tests failed with code 0xc0000005. Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2021-09-23 11:00:11 +00:00
expect(selectFired).to.be.false();
expect(device).to.equal('');
});
it('returns a device when select-hid-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
expect(details.frame).to.have.ownProperty('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
feat: add support for WebHID (#30213) * feat: add support for WebHID * Apply suggestions from code review Co-authored-by: Jeremy Rose <jeremya@chromium.org> * Address review feedback * Address review feedback * chore: clear granted_devices on navigation Also added test to verify devices get cleared * fixup testing for device clear * make sure navigator.hid.getDevices is run on correct frame * clear granted devices on RenderFrameHost deletion/change * manage device permissions per RenderFrameHost This change makes sure we don't clear device permission prematurely due to child frame navigation * Update shell/browser/api/electron_api_web_contents.cc Co-authored-by: Jeremy Rose <jeremya@chromium.org> * apply review feedback from @zcbenz * Match upstream ObjectMap This change matches what ObjectPermissionContextBase uses to cache object permissions: https://source.chromium.org/chromium/chromium/src/+/main:components/permissions/object_permission_context_base.h;l=52;drc=8f95b5eab2797a3e26bba299f3b0df85bfc98bf5;bpv=1;bpt=0 The main reason for this was to resolve this crash on Win x64: ok 2 WebContentsView doesn't crash when GCed during allocation Received fatal exception EXCEPTION_ACCESS_VIOLATION Backtrace: gin::WrappableBase::SecondWeakCallback [0x00007FF6F2AFA005+133] (o:\gin\wrappable.cc:53) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacks [0x00007FF6F028F9AB+171] (o:\v8\src\handles\global-handles.cc:1400) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacksFromTask [0x00007FF6F028F867+391] (o:\v8\src\handles\global-handles.cc:1387) node::PerIsolatePlatformData::RunForegroundTask [0x00007FF6F3B4D065+317] (o:\third_party\electron_node\src\node_platform.cc:415) node::PerIsolatePlatformData::FlushForegroundTasksInternal [0x00007FF6F3B4C424+776] (o:\third_party\electron_node\src\node_platform.cc:479) uv_run [0x00007FF6F2DDD07C+492] (o:\third_party\electron_node\deps\uv\src\win\core.c:609) electron::NodeBindings::UvRunOnce [0x00007FF6EEE1E036+294] (o:\electron\shell\common\node_bindings.cc:631) base::TaskAnnotator::RunTask [0x00007FF6F2318A19+457] (o:\base\task\common\task_annotator.cc:178) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl [0x00007FF6F2E6F553+963] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:361) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork [0x00007FF6F2E6EC69+137] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:266) base::MessagePumpForUI::DoRunLoop [0x00007FF6F235AA58+216] (o:\base\message_loop\message_pump_win.cc:221) base::MessagePumpWin::Run [0x00007FF6F235A01A+106] (o:\base\message_loop\message_pump_win.cc:79) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run [0x00007FF6F2E702DA+682] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:470) base::RunLoop::Run [0x00007FF6F22F95BA+842] (o:\base\run_loop.cc:136) content::BrowserMainLoop::RunMainMessageLoop [0x00007FF6F14423CC+208] (o:\content\browser\browser_main_loop.cc:990) content::BrowserMainRunnerImpl::Run [0x00007FF6F144402F+143] (o:\content\browser\browser_main_runner_impl.cc:153) content::BrowserMain [0x00007FF6F143F911+257] (o:\content\browser\browser_main.cc:49) content::RunBrowserProcessMain [0x00007FF6EFFA7D18+112] (o:\content\app\content_main_runner_impl.cc:608) content::ContentMainRunnerImpl::RunBrowser [0x00007FF6EFFA8CF4+1220] (o:\content\app\content_main_runner_impl.cc:1104) content::ContentMainRunnerImpl::Run [0x00007FF6EFFA87C9+393] (o:\content\app\content_main_runner_impl.cc:971) content::RunContentProcess [0x00007FF6EFFA73BD+733] (o:\content\app\content_main.cc:394) content::ContentMain [0x00007FF6EFFA79E1+54] (o:\content\app\content_main.cc:422) wWinMain [0x00007FF6EECA1535+889] (o:\electron\shell\app\electron_main.cc:291) __scrt_common_main_seh [0x00007FF6F6F88482+262] (d:\A01\_work\6\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288) BaseThreadInitThunk [0x00007FFEC0087034+20] RtlUserThreadStart [0x00007FFEC1F02651+33] ✗ Electron tests failed with code 0xc0000005. Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2021-09-23 11:00:11 +00:00
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
} else {
expect(device).to.equal('');
}
if (process.arch === 'arm64' || process.arch === 'arm') {
// arm CI returns HID devices - this block may need to change if CI hardware changes.
expect(haveDevices).to.be.true();
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(frame).to.not.be.empty();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
const device = await requestDevices();
feat: add support for WebHID (#30213) * feat: add support for WebHID * Apply suggestions from code review Co-authored-by: Jeremy Rose <jeremya@chromium.org> * Address review feedback * Address review feedback * chore: clear granted_devices on navigation Also added test to verify devices get cleared * fixup testing for device clear * make sure navigator.hid.getDevices is run on correct frame * clear granted devices on RenderFrameHost deletion/change * manage device permissions per RenderFrameHost This change makes sure we don't clear device permission prematurely due to child frame navigation * Update shell/browser/api/electron_api_web_contents.cc Co-authored-by: Jeremy Rose <jeremya@chromium.org> * apply review feedback from @zcbenz * Match upstream ObjectMap This change matches what ObjectPermissionContextBase uses to cache object permissions: https://source.chromium.org/chromium/chromium/src/+/main:components/permissions/object_permission_context_base.h;l=52;drc=8f95b5eab2797a3e26bba299f3b0df85bfc98bf5;bpv=1;bpt=0 The main reason for this was to resolve this crash on Win x64: ok 2 WebContentsView doesn't crash when GCed during allocation Received fatal exception EXCEPTION_ACCESS_VIOLATION Backtrace: gin::WrappableBase::SecondWeakCallback [0x00007FF6F2AFA005+133] (o:\gin\wrappable.cc:53) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacks [0x00007FF6F028F9AB+171] (o:\v8\src\handles\global-handles.cc:1400) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacksFromTask [0x00007FF6F028F867+391] (o:\v8\src\handles\global-handles.cc:1387) node::PerIsolatePlatformData::RunForegroundTask [0x00007FF6F3B4D065+317] (o:\third_party\electron_node\src\node_platform.cc:415) node::PerIsolatePlatformData::FlushForegroundTasksInternal [0x00007FF6F3B4C424+776] (o:\third_party\electron_node\src\node_platform.cc:479) uv_run [0x00007FF6F2DDD07C+492] (o:\third_party\electron_node\deps\uv\src\win\core.c:609) electron::NodeBindings::UvRunOnce [0x00007FF6EEE1E036+294] (o:\electron\shell\common\node_bindings.cc:631) base::TaskAnnotator::RunTask [0x00007FF6F2318A19+457] (o:\base\task\common\task_annotator.cc:178) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl [0x00007FF6F2E6F553+963] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:361) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork [0x00007FF6F2E6EC69+137] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:266) base::MessagePumpForUI::DoRunLoop [0x00007FF6F235AA58+216] (o:\base\message_loop\message_pump_win.cc:221) base::MessagePumpWin::Run [0x00007FF6F235A01A+106] (o:\base\message_loop\message_pump_win.cc:79) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run [0x00007FF6F2E702DA+682] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:470) base::RunLoop::Run [0x00007FF6F22F95BA+842] (o:\base\run_loop.cc:136) content::BrowserMainLoop::RunMainMessageLoop [0x00007FF6F14423CC+208] (o:\content\browser\browser_main_loop.cc:990) content::BrowserMainRunnerImpl::Run [0x00007FF6F144402F+143] (o:\content\browser\browser_main_runner_impl.cc:153) content::BrowserMain [0x00007FF6F143F911+257] (o:\content\browser\browser_main.cc:49) content::RunBrowserProcessMain [0x00007FF6EFFA7D18+112] (o:\content\app\content_main_runner_impl.cc:608) content::ContentMainRunnerImpl::RunBrowser [0x00007FF6EFFA8CF4+1220] (o:\content\app\content_main_runner_impl.cc:1104) content::ContentMainRunnerImpl::Run [0x00007FF6EFFA87C9+393] (o:\content\app\content_main_runner_impl.cc:971) content::RunContentProcess [0x00007FF6EFFA73BD+733] (o:\content\app\content_main.cc:394) content::ContentMain [0x00007FF6EFFA79E1+54] (o:\content\app\content_main.cc:422) wWinMain [0x00007FF6EECA1535+889] (o:\electron\shell\app\electron_main.cc:291) __scrt_common_main_seh [0x00007FF6F6F88482+262] (d:\A01\_work\6\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288) BaseThreadInitThunk [0x00007FFEC0087034+20] RtlUserThreadStart [0x00007FFEC1F02651+33] ✗ Electron tests failed with code 0xc0000005. Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2021-09-23 11:00:11 +00:00
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal('');
}
});
chore: bump chromium to 102.0.4989.0 (main) (#33557) * chore: bump chromium in DEPS to 102.0.4975.0 * chore: bump chromium in DEPS to 102.0.4977.0 * chore: update patches * Remove parameter of OnGpuProcessCrashed() https://chromium-review.googlesource.com/c/chromium/src/+/3543396 * hid: Add exclusionFilters option to requestDevice https://chromium-review.googlesource.com/c/chromium/src/+/3478175 * chore: bump chromium in DEPS to 102.0.4979.0 * chore: bump chromium in DEPS to 102.0.4981.0 * chore: update patches * Deny notification/push permission for documents in non-standard StoragePartitions https://chromium-review.googlesource.com/c/chromium/src/+/3257305 * Improve FrameTreeNode tracking in URLLoaderNetworkContext https://chromium-review.googlesource.com/c/chromium/src/+/3341866 * fixup! Remove parameter of OnGpuProcessCrashed() * chore: fix lint * Reland "Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome" https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * chore: bump chromium in DEPS to 102.0.4983.0 * Ensure EyeDropperView does not access a destroyed window https://chromium-review.googlesource.com/c/chromium/src/+/3561542 * ci: don't delete dawn .git directory 83901: Adds a generated file with the dawn git hash encoded at build time. | https://dawn-review.googlesource.com/c/dawn/+/83901 * ci: update Windows toolchain 3550827: New toolchain for Windows 10 20348 SDK | https://chromium-review.googlesource.com/c/chromium/src/+/3550827 * chore: bump chromium in DEPS to 102.0.4985.0 * chore: update patches * chore: bump chromium in DEPS to 102.0.4987.0 * chore: update patches * 3563432: codehealth: remove uses of DictionaryValue in cbui/webui https://chromium-review.googlesource.com/c/chromium/src/+/3563432 * chore: update patches after rebase * Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * 3565724: Preserve "proper method names" as-is in error.stack. https://chromium-review.googlesource.com/c/v8/v8/+/3565724 * chore: bump chromium in DEPS to 102.0.4989.0 * chore: update patches * fixup ci: don't delete dawn .git directory for Windows * 3560843: Remove multi-parameter version of gfx::Rect[F]::Inset() https://chromium-review.googlesource.com/c/chromium/src/+/3560843 * 3572711: Remove unused IDS_PDF_TOOLTIP_ROTATE_CW resource. https://chromium-review.googlesource.com/c/chromium/src/+/3572711 * 3572926: Reland "[Sysroot] Switch to Debian Bullseye stable" https://chromium-review.googlesource.com/c/chromium/src/+/3572926 * build: fixup sysroots with electron specific dependencies * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * fixup 3565724: Preserve "proper method names" as-is in error.stack. * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * test: add spec for navigator.hid.requestDevice({ exclusionFilters: [...] } * fixup 3565724: Preserve "proper method names" as-is in error.stack. * ci: use python3 to get the windows toolchain profile 3525960: Explicitly run everything with python3 | https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/3525960 * chore: add diagnostic logging * fix: try calling process.crash() * chore: remove logging Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2022-04-12 11:19:14 +00:00
it('excludes a device when a exclusionFilter is specified', async () => {
chore: bump chromium to 102.0.4989.0 (main) (#33557) * chore: bump chromium in DEPS to 102.0.4975.0 * chore: bump chromium in DEPS to 102.0.4977.0 * chore: update patches * Remove parameter of OnGpuProcessCrashed() https://chromium-review.googlesource.com/c/chromium/src/+/3543396 * hid: Add exclusionFilters option to requestDevice https://chromium-review.googlesource.com/c/chromium/src/+/3478175 * chore: bump chromium in DEPS to 102.0.4979.0 * chore: bump chromium in DEPS to 102.0.4981.0 * chore: update patches * Deny notification/push permission for documents in non-standard StoragePartitions https://chromium-review.googlesource.com/c/chromium/src/+/3257305 * Improve FrameTreeNode tracking in URLLoaderNetworkContext https://chromium-review.googlesource.com/c/chromium/src/+/3341866 * fixup! Remove parameter of OnGpuProcessCrashed() * chore: fix lint * Reland "Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome" https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * chore: bump chromium in DEPS to 102.0.4983.0 * Ensure EyeDropperView does not access a destroyed window https://chromium-review.googlesource.com/c/chromium/src/+/3561542 * ci: don't delete dawn .git directory 83901: Adds a generated file with the dawn git hash encoded at build time. | https://dawn-review.googlesource.com/c/dawn/+/83901 * ci: update Windows toolchain 3550827: New toolchain for Windows 10 20348 SDK | https://chromium-review.googlesource.com/c/chromium/src/+/3550827 * chore: bump chromium in DEPS to 102.0.4985.0 * chore: update patches * chore: bump chromium in DEPS to 102.0.4987.0 * chore: update patches * 3563432: codehealth: remove uses of DictionaryValue in cbui/webui https://chromium-review.googlesource.com/c/chromium/src/+/3563432 * chore: update patches after rebase * Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * 3565724: Preserve "proper method names" as-is in error.stack. https://chromium-review.googlesource.com/c/v8/v8/+/3565724 * chore: bump chromium in DEPS to 102.0.4989.0 * chore: update patches * fixup ci: don't delete dawn .git directory for Windows * 3560843: Remove multi-parameter version of gfx::Rect[F]::Inset() https://chromium-review.googlesource.com/c/chromium/src/+/3560843 * 3572711: Remove unused IDS_PDF_TOOLTIP_ROTATE_CW resource. https://chromium-review.googlesource.com/c/chromium/src/+/3572711 * 3572926: Reland "[Sysroot] Switch to Debian Bullseye stable" https://chromium-review.googlesource.com/c/chromium/src/+/3572926 * build: fixup sysroots with electron specific dependencies * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * fixup 3565724: Preserve "proper method names" as-is in error.stack. * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * test: add spec for navigator.hid.requestDevice({ exclusionFilters: [...] } * fixup 3565724: Preserve "proper method names" as-is in error.stack. * ci: use python3 to get the windows toolchain profile 3525960: Explicitly run everything with python3 | https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/3525960 * chore: add diagnostic logging * fix: try calling process.crash() * chore: remove logging Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2022-04-12 11:19:14 +00:00
const exclusionFilters = <any>[];
let haveDevices = false;
let checkForExcludedDevice = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
if (checkForExcludedDevice) {
const compareDevice = {
vendorId: device.vendorId,
productId: device.productId
};
expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
} else {
haveDevices = true;
exclusionFilters.push({
vendorId: device.vendorId,
productId: device.productId
});
return true;
}
}
});
}
callback();
});
await requestDevices();
chore: bump chromium to 102.0.4989.0 (main) (#33557) * chore: bump chromium in DEPS to 102.0.4975.0 * chore: bump chromium in DEPS to 102.0.4977.0 * chore: update patches * Remove parameter of OnGpuProcessCrashed() https://chromium-review.googlesource.com/c/chromium/src/+/3543396 * hid: Add exclusionFilters option to requestDevice https://chromium-review.googlesource.com/c/chromium/src/+/3478175 * chore: bump chromium in DEPS to 102.0.4979.0 * chore: bump chromium in DEPS to 102.0.4981.0 * chore: update patches * Deny notification/push permission for documents in non-standard StoragePartitions https://chromium-review.googlesource.com/c/chromium/src/+/3257305 * Improve FrameTreeNode tracking in URLLoaderNetworkContext https://chromium-review.googlesource.com/c/chromium/src/+/3341866 * fixup! Remove parameter of OnGpuProcessCrashed() * chore: fix lint * Reland "Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome" https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * chore: bump chromium in DEPS to 102.0.4983.0 * Ensure EyeDropperView does not access a destroyed window https://chromium-review.googlesource.com/c/chromium/src/+/3561542 * ci: don't delete dawn .git directory 83901: Adds a generated file with the dawn git hash encoded at build time. | https://dawn-review.googlesource.com/c/dawn/+/83901 * ci: update Windows toolchain 3550827: New toolchain for Windows 10 20348 SDK | https://chromium-review.googlesource.com/c/chromium/src/+/3550827 * chore: bump chromium in DEPS to 102.0.4985.0 * chore: update patches * chore: bump chromium in DEPS to 102.0.4987.0 * chore: update patches * 3563432: codehealth: remove uses of DictionaryValue in cbui/webui https://chromium-review.googlesource.com/c/chromium/src/+/3563432 * chore: update patches after rebase * Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * 3565724: Preserve "proper method names" as-is in error.stack. https://chromium-review.googlesource.com/c/v8/v8/+/3565724 * chore: bump chromium in DEPS to 102.0.4989.0 * chore: update patches * fixup ci: don't delete dawn .git directory for Windows * 3560843: Remove multi-parameter version of gfx::Rect[F]::Inset() https://chromium-review.googlesource.com/c/chromium/src/+/3560843 * 3572711: Remove unused IDS_PDF_TOOLTIP_ROTATE_CW resource. https://chromium-review.googlesource.com/c/chromium/src/+/3572711 * 3572926: Reland "[Sysroot] Switch to Debian Bullseye stable" https://chromium-review.googlesource.com/c/chromium/src/+/3572926 * build: fixup sysroots with electron specific dependencies * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * fixup 3565724: Preserve "proper method names" as-is in error.stack. * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * test: add spec for navigator.hid.requestDevice({ exclusionFilters: [...] } * fixup 3565724: Preserve "proper method names" as-is in error.stack. * ci: use python3 to get the windows toolchain profile 3525960: Explicitly run everything with python3 | https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/3525960 * chore: add diagnostic logging * fix: try calling process.crash() * chore: remove logging Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2022-04-12 11:19:14 +00:00
if (haveDevices) {
// We have devices to exclude, so check if exclusionFilters work
chore: bump chromium to 102.0.4989.0 (main) (#33557) * chore: bump chromium in DEPS to 102.0.4975.0 * chore: bump chromium in DEPS to 102.0.4977.0 * chore: update patches * Remove parameter of OnGpuProcessCrashed() https://chromium-review.googlesource.com/c/chromium/src/+/3543396 * hid: Add exclusionFilters option to requestDevice https://chromium-review.googlesource.com/c/chromium/src/+/3478175 * chore: bump chromium in DEPS to 102.0.4979.0 * chore: bump chromium in DEPS to 102.0.4981.0 * chore: update patches * Deny notification/push permission for documents in non-standard StoragePartitions https://chromium-review.googlesource.com/c/chromium/src/+/3257305 * Improve FrameTreeNode tracking in URLLoaderNetworkContext https://chromium-review.googlesource.com/c/chromium/src/+/3341866 * fixup! Remove parameter of OnGpuProcessCrashed() * chore: fix lint * Reland "Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome" https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * chore: bump chromium in DEPS to 102.0.4983.0 * Ensure EyeDropperView does not access a destroyed window https://chromium-review.googlesource.com/c/chromium/src/+/3561542 * ci: don't delete dawn .git directory 83901: Adds a generated file with the dawn git hash encoded at build time. | https://dawn-review.googlesource.com/c/dawn/+/83901 * ci: update Windows toolchain 3550827: New toolchain for Windows 10 20348 SDK | https://chromium-review.googlesource.com/c/chromium/src/+/3550827 * chore: bump chromium in DEPS to 102.0.4985.0 * chore: update patches * chore: bump chromium in DEPS to 102.0.4987.0 * chore: update patches * 3563432: codehealth: remove uses of DictionaryValue in cbui/webui https://chromium-review.googlesource.com/c/chromium/src/+/3563432 * chore: update patches after rebase * Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * 3565724: Preserve "proper method names" as-is in error.stack. https://chromium-review.googlesource.com/c/v8/v8/+/3565724 * chore: bump chromium in DEPS to 102.0.4989.0 * chore: update patches * fixup ci: don't delete dawn .git directory for Windows * 3560843: Remove multi-parameter version of gfx::Rect[F]::Inset() https://chromium-review.googlesource.com/c/chromium/src/+/3560843 * 3572711: Remove unused IDS_PDF_TOOLTIP_ROTATE_CW resource. https://chromium-review.googlesource.com/c/chromium/src/+/3572711 * 3572926: Reland "[Sysroot] Switch to Debian Bullseye stable" https://chromium-review.googlesource.com/c/chromium/src/+/3572926 * build: fixup sysroots with electron specific dependencies * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * fixup 3565724: Preserve "proper method names" as-is in error.stack. * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * test: add spec for navigator.hid.requestDevice({ exclusionFilters: [...] } * fixup 3565724: Preserve "proper method names" as-is in error.stack. * ci: use python3 to get the windows toolchain profile 3525960: Explicitly run everything with python3 | https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/3525960 * chore: add diagnostic logging * fix: try calling process.crash() * chore: remove logging Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2022-04-12 11:19:14 +00:00
checkForExcludedDevice = true;
await w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
chore: bump chromium to 102.0.4989.0 (main) (#33557) * chore: bump chromium in DEPS to 102.0.4975.0 * chore: bump chromium in DEPS to 102.0.4977.0 * chore: update patches * Remove parameter of OnGpuProcessCrashed() https://chromium-review.googlesource.com/c/chromium/src/+/3543396 * hid: Add exclusionFilters option to requestDevice https://chromium-review.googlesource.com/c/chromium/src/+/3478175 * chore: bump chromium in DEPS to 102.0.4979.0 * chore: bump chromium in DEPS to 102.0.4981.0 * chore: update patches * Deny notification/push permission for documents in non-standard StoragePartitions https://chromium-review.googlesource.com/c/chromium/src/+/3257305 * Improve FrameTreeNode tracking in URLLoaderNetworkContext https://chromium-review.googlesource.com/c/chromium/src/+/3341866 * fixup! Remove parameter of OnGpuProcessCrashed() * chore: fix lint * Reland "Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome" https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * chore: bump chromium in DEPS to 102.0.4983.0 * Ensure EyeDropperView does not access a destroyed window https://chromium-review.googlesource.com/c/chromium/src/+/3561542 * ci: don't delete dawn .git directory 83901: Adds a generated file with the dawn git hash encoded at build time. | https://dawn-review.googlesource.com/c/dawn/+/83901 * ci: update Windows toolchain 3550827: New toolchain for Windows 10 20348 SDK | https://chromium-review.googlesource.com/c/chromium/src/+/3550827 * chore: bump chromium in DEPS to 102.0.4985.0 * chore: update patches * chore: bump chromium in DEPS to 102.0.4987.0 * chore: update patches * 3563432: codehealth: remove uses of DictionaryValue in cbui/webui https://chromium-review.googlesource.com/c/chromium/src/+/3563432 * chore: update patches after rebase * Use gfx::Insets[F]::TLBR() and gfx::Insets[F]::VH() in the rest of Chrome https://chromium-review.googlesource.com/c/chromium/src/+/3554236 * 3565724: Preserve "proper method names" as-is in error.stack. https://chromium-review.googlesource.com/c/v8/v8/+/3565724 * chore: bump chromium in DEPS to 102.0.4989.0 * chore: update patches * fixup ci: don't delete dawn .git directory for Windows * 3560843: Remove multi-parameter version of gfx::Rect[F]::Inset() https://chromium-review.googlesource.com/c/chromium/src/+/3560843 * 3572711: Remove unused IDS_PDF_TOOLTIP_ROTATE_CW resource. https://chromium-review.googlesource.com/c/chromium/src/+/3572711 * 3572926: Reland "[Sysroot] Switch to Debian Bullseye stable" https://chromium-review.googlesource.com/c/chromium/src/+/3572926 * build: fixup sysroots with electron specific dependencies * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * fixup 3565724: Preserve "proper method names" as-is in error.stack. * fixup Remove multi-parameter version of gfx::Rect[F]::Inset() * test: add spec for navigator.hid.requestDevice({ exclusionFilters: [...] } * fixup 3565724: Preserve "proper method names" as-is in error.stack. * ci: use python3 to get the windows toolchain profile 3525960: Explicitly run everything with python3 | https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/3525960 * chore: add diagnostic logging * fix: try calling process.crash() * chore: remove logging Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2022-04-12 11:19:14 +00:00
`, true);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('hid-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice = await w.webContents.executeJavaScript(`
navigator.hid.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
name: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
feat: add support for WebHID (#30213) * feat: add support for WebHID * Apply suggestions from code review Co-authored-by: Jeremy Rose <jeremya@chromium.org> * Address review feedback * Address review feedback * chore: clear granted_devices on navigation Also added test to verify devices get cleared * fixup testing for device clear * make sure navigator.hid.getDevices is run on correct frame * clear granted devices on RenderFrameHost deletion/change * manage device permissions per RenderFrameHost This change makes sure we don't clear device permission prematurely due to child frame navigation * Update shell/browser/api/electron_api_web_contents.cc Co-authored-by: Jeremy Rose <jeremya@chromium.org> * apply review feedback from @zcbenz * Match upstream ObjectMap This change matches what ObjectPermissionContextBase uses to cache object permissions: https://source.chromium.org/chromium/chromium/src/+/main:components/permissions/object_permission_context_base.h;l=52;drc=8f95b5eab2797a3e26bba299f3b0df85bfc98bf5;bpv=1;bpt=0 The main reason for this was to resolve this crash on Win x64: ok 2 WebContentsView doesn't crash when GCed during allocation Received fatal exception EXCEPTION_ACCESS_VIOLATION Backtrace: gin::WrappableBase::SecondWeakCallback [0x00007FF6F2AFA005+133] (o:\gin\wrappable.cc:53) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacks [0x00007FF6F028F9AB+171] (o:\v8\src\handles\global-handles.cc:1400) v8::internal::GlobalHandles::InvokeSecondPassPhantomCallbacksFromTask [0x00007FF6F028F867+391] (o:\v8\src\handles\global-handles.cc:1387) node::PerIsolatePlatformData::RunForegroundTask [0x00007FF6F3B4D065+317] (o:\third_party\electron_node\src\node_platform.cc:415) node::PerIsolatePlatformData::FlushForegroundTasksInternal [0x00007FF6F3B4C424+776] (o:\third_party\electron_node\src\node_platform.cc:479) uv_run [0x00007FF6F2DDD07C+492] (o:\third_party\electron_node\deps\uv\src\win\core.c:609) electron::NodeBindings::UvRunOnce [0x00007FF6EEE1E036+294] (o:\electron\shell\common\node_bindings.cc:631) base::TaskAnnotator::RunTask [0x00007FF6F2318A19+457] (o:\base\task\common\task_annotator.cc:178) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl [0x00007FF6F2E6F553+963] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:361) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork [0x00007FF6F2E6EC69+137] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:266) base::MessagePumpForUI::DoRunLoop [0x00007FF6F235AA58+216] (o:\base\message_loop\message_pump_win.cc:221) base::MessagePumpWin::Run [0x00007FF6F235A01A+106] (o:\base\message_loop\message_pump_win.cc:79) base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run [0x00007FF6F2E702DA+682] (o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:470) base::RunLoop::Run [0x00007FF6F22F95BA+842] (o:\base\run_loop.cc:136) content::BrowserMainLoop::RunMainMessageLoop [0x00007FF6F14423CC+208] (o:\content\browser\browser_main_loop.cc:990) content::BrowserMainRunnerImpl::Run [0x00007FF6F144402F+143] (o:\content\browser\browser_main_runner_impl.cc:153) content::BrowserMain [0x00007FF6F143F911+257] (o:\content\browser\browser_main.cc:49) content::RunBrowserProcessMain [0x00007FF6EFFA7D18+112] (o:\content\app\content_main_runner_impl.cc:608) content::ContentMainRunnerImpl::RunBrowser [0x00007FF6EFFA8CF4+1220] (o:\content\app\content_main_runner_impl.cc:1104) content::ContentMainRunnerImpl::Run [0x00007FF6EFFA87C9+393] (o:\content\app\content_main_runner_impl.cc:971) content::RunContentProcess [0x00007FF6EFFA73BD+733] (o:\content\app\content_main.cc:394) content::ContentMain [0x00007FF6EFFA79E1+54] (o:\content\app\content_main.cc:422) wWinMain [0x00007FF6EECA1535+889] (o:\electron\shell\app\electron_main.cc:291) __scrt_common_main_seh [0x00007FF6F6F88482+262] (d:\A01\_work\6\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288) BaseThreadInitThunk [0x00007FFEC0087034+20] RtlUserThreadStart [0x00007FFEC1F02651+33] ✗ Electron tests failed with code 0xc0000005. Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2021-09-23 11:00:11 +00:00
});