electron/spec/extensions-spec.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1249 lines
51 KiB
TypeScript
Raw Normal View History

import { expect } from 'chai';
import { app, session, BrowserWindow, ipcMain, WebContents, Extension, Session } from 'electron/main';
import { closeAllWindows, closeWindow } from './lib/window-helpers';
import * as http from 'node:http';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as WebSocket from 'ws';
import { emittedNTimes, emittedUntil } from './lib/events-helpers';
import { ifit, listen } from './lib/spec-helpers';
import { once } from 'node:events';
2020-03-20 20:28:31 +00:00
const uuid = require('uuid');
const fixtures = path.join(__dirname, 'fixtures');
describe('chrome extensions', () => {
const emptyPage = '<script>console.log("loaded")</script>';
// NB. extensions are only allowed on http://, https:// and ftp:// (!) urls by default.
let server: http.Server;
let url: string;
let port: number;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/cors') {
res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
}
res.end(emptyPage);
});
const wss = new WebSocket.Server({ noServer: true });
wss.on('connection', function connection (ws) {
ws.on('message', function incoming (message) {
if (message === 'foo') {
ws.send('bar');
}
});
});
({ port, url } = await listen(server));
});
after(() => {
server.close();
});
afterEach(closeAllWindows);
afterEach(() => {
for (const e of session.defaultSession.getAllExtensions()) {
session.defaultSession.removeExtension(e.id);
}
});
it('does not crash when using chrome.management', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
await w.loadURL('about:blank');
const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
const args: any = await promise;
const wc: Electron.WebContents = args[1];
await expect(wc.executeJavaScript(`
(() => {
return new Promise((resolve) => {
chrome.management.getSelf((info) => {
resolve(info);
});
})
})();
`)).to.eventually.have.property('id');
});
describe('host_permissions', async () => {
let customSession: Session;
let w: BrowserWindow;
beforeEach(() => {
customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
w = new BrowserWindow({
show: false,
webPreferences: {
session: customSession,
sandbox: true
}
});
});
afterEach(closeAllWindows);
it('recognize malformed host permissions', async () => {
await w.loadURL(url);
const extPath = path.join(fixtures, 'extensions', 'host-permissions', 'malformed');
customSession.loadExtension(extPath);
const warning = await new Promise(resolve => { process.on('warning', resolve); });
const malformedHost = /Permission 'malformed_host' is unknown or URL pattern is malformed/;
expect(warning).to.match(malformedHost);
});
it('can grant special privileges to urls with host permissions', async () => {
const extPath = path.join(fixtures, 'extensions', 'host-permissions', 'privileged-tab-info');
await customSession.loadExtension(extPath);
await w.loadURL(url);
const message = { method: 'query' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.have.lengthOf(1);
const tab = response[0];
expect(tab).to.have.property('url').that.is.a('string');
expect(tab).to.have.property('title').that.is.a('string');
expect(tab).to.have.property('active').that.is.a('boolean');
expect(tab).to.have.property('autoDiscardable').that.is.a('boolean');
expect(tab).to.have.property('discarded').that.is.a('boolean');
expect(tab).to.have.property('groupId').that.is.a('number');
expect(tab).to.have.property('highlighted').that.is.a('boolean');
expect(tab).to.have.property('id').that.is.a('number');
expect(tab).to.have.property('incognito').that.is.a('boolean');
expect(tab).to.have.property('index').that.is.a('number');
expect(tab).to.have.property('pinned').that.is.a('boolean');
expect(tab).to.have.property('selected').that.is.a('boolean');
expect(tab).to.have.property('windowId').that.is.a('number');
});
});
it('supports minimum_chrome_version manifest key', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const w = new BrowserWindow({
show: false,
webPreferences: {
session: customSession,
sandbox: true
}
});
await w.loadURL('about:blank');
const extPath = path.join(fixtures, 'extensions', 'minimum-chrome-version');
const load = customSession.loadExtension(extPath);
await expect(load).to.eventually.be.rejectedWith(
`Loading extension at ${extPath} failed with: This extension requires Chromium version 999 or greater.`
);
});
it('can open WebSQLDatabase in a background page', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
await w.loadURL('about:blank');
const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
const args: any = await promise;
const wc: Electron.WebContents = args[1];
await expect(wc.executeJavaScript('(()=>{try{openDatabase("t", "1.0", "test", 2e5);return true;}catch(e){throw e}})()')).to.not.be.rejected();
});
function fetch (contents: WebContents, url: string) {
return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`);
}
it('bypasses CORS in requests made from extensions', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
await w.loadURL(`${extension.url}bare-page.html`);
await expect(fetch(w.webContents, `${url}/cors`)).to.not.be.rejectedWith(TypeError);
});
it('loads an extension', async () => {
// NB. we have to use a persist: session (i.e. non-OTR) because the
// extension registry is redirected to the main session. so installing an
// extension in an in-memory session results in it being installed in the
// default session.
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
2019-11-01 20:37:02 +00:00
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('red');
});
it('does not crash when loading an extension with missing manifest', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'missing-manifest'));
await expect(promise).to.eventually.be.rejectedWith(/Manifest file is missing or unreadable/);
});
it('does not crash when failing to load an extension', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'load-error'));
await expect(promise).to.eventually.be.rejected();
});
it('serializes a loaded extension', async () => {
const extensionPath = path.join(fixtures, 'extensions', 'red-bg');
const manifest = JSON.parse(fs.readFileSync(path.join(extensionPath, 'manifest.json'), 'utf-8'));
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const extension = await customSession.loadExtension(extensionPath);
expect(extension.id).to.be.a('string');
expect(extension.name).to.be.a('string');
expect(extension.path).to.be.a('string');
expect(extension.version).to.be.a('string');
expect(extension.url).to.be.a('string');
expect(extension.manifest).to.deep.equal(manifest);
});
it('removes an extension', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
{
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('red');
}
customSession.removeExtension(id);
{
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('');
}
});
it('emits extension lifecycle events', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const loadedPromise = once(customSession, 'extension-loaded');
const readyPromise = emittedUntil(customSession, 'extension-ready', (event: Event, extension: Extension) => {
chore: bump chromium to 110.0.5415.0 (main) (#36186) * chore: bump chromium in DEPS to 109.0.5386.0 * chore: bump chromium in DEPS to 109.0.5388.0 * chore: bump chromium in DEPS to 109.0.5390.0 * chore: bump chromium in DEPS to 109.0.5392.0 * chore: bump chromium in DEPS to 109.0.5394.0 * chore: bump chromium in DEPS to 109.0.5396.0 * chore: bump chromium in DEPS to 109.0.5398.0 * chore: bump chromium in DEPS to 109.0.5400.0 * chore: update galactus * chore: bump chromium in DEPS to 109.0.5402.0 * chore: bump chromium in DEPS to 109.0.5403.0 * chore: bump chromium in DEPS to 109.0.5406.0 * chore: update patches * 4004247: Delete unused DocumentWebContentsDelegate Ref: https://chromium-review.googlesource.com/c/chromium/src/+/4004247 * chore: bump chromium in DEPS to 109.0.5408.1 * chore: update patches * 3949284: Support pkey debug mode without pkey 0 access Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3949284 * chore: bump chromium in DEPS to 109.0.5410.0 * chore: update patches * 4000944: [Extensions] Create an API directory in //chrome/renderer/extensions Ref: https://chromium-review.googlesource.com/c/chromium/src/+/4000944 * 3988524: Remove DocumentOverlayWindowViews | https://chromium-review.googlesource.com/c/chromium/src/+/3988524 Co-authored-by: George Xu <33054982+georgexu99@users.noreply.github.com> * chore: bump chromium in DEPS to 109.0.5412.0 * chore: update patches * 3984022: Add AddChildWindowToBrowser to DisplayClient mojo interface Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3984022 * 3957079: Delete the CryptoToken component extension and internal API Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3957079 * 4004421: Migreate ScopedAllowIO to ScopedAllowBlocking Ref: https://chromium-review.googlesource.com/c/chromium/src/+/4004421 Co-authored-by: George Xu <georgexu99@users.noreply.github.com> * chore: bump chromium in DEPS to 109.0.5414.0 * chore: update patches * 4016180: Split PPAPI Mojo interfaces out of RenderFrameHostImpl. Ref: https://chromium-review.googlesource.com/c/chromium/src/+/4016180 * 3970838: [MPArch] Convert HostZoomMap and ZoomController off of RenderViewHost ids Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3970838 * 3997795: Don't add Chromium as a login item Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3997795 * 3993482: Remove RefCountedString::TakeString Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3993482 * 3990749: Allow forward-declared sources in base::ScopedObservation<> Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3990749 * fixup! 3957079: Delete the CryptoToken component extension and internal API * chore: bump chromium in DEPS to 110.0.5415.0 * 3883790: Move devtools_frame_token to the RenderFrameHost, to preserve RFH identity across MPArch activations. https://chromium-review.googlesource.com/c/chromium/src/+/3883790 * 4022205: Move license tooling into //tools/licenses https://chromium-review.googlesource.com/c/chromium/src/+/4022205 * chore: fixup patch indices * fixup! 3957079: Delete the CryptoToken component extension and internal API * 4008687: Finish ScopedAllowIO migration https://chromium-review.googlesource.com/c/chromium/src/+/4008687 * 3991548: Move WindowButtonOrderObserver and WindowFrameAction to LinuxUi https://chromium-review.googlesource.com/c/chromium/src/+/3991548 * fixup! 3984022: Add AddChildWindowToBrowser to DisplayClient mojo interface * 4016595: Migrate non-default ScopedObservation<> instantiations to ScopedObservationTraits<> in chrome/browser/ https://chromium-review.googlesource.com/c/chromium/src/+/4016595 * 4000481: Rename :chromedriver to :chromedriver_server Ref: https://chromium-review.googlesource.com/c/chromium/src/+/4000481 * 4008687: Finish ScopedAllowIO migration https://chromium-review.googlesource.com/c/chromium/src/+/4008687 * 3988524: Remove DocumentOverlayWindowViews https://chromium-review.googlesource.com/c/chromium/src/+/3988524 * fixup! 3997795: Don't add Chromium as a login item * chore: fixup patches * 3996872: Plumb input event task runner to EventFactoryEvdev https://chromium-review.googlesource.com/c/chromium/src/+/3996872 * 4014994: Enable SiteIsolationForGuests by default. https://chromium-review.googlesource.com/c/chromium/src/+/4014994 * chore: adopt new thread restrictions api for //electron (#36357) chore: add thread blocking api * fixup! 4014994: Enable SiteIsolationForGuests by default. * pull parent HWND for dialogs on ui thread * chore: set parent_window in MessageBoxSettings * chore: remove redundant patch * chore: revert accidental deletion * chore: update patches Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: Samuel Attard <sattard@salesforce.com> Co-authored-by: Keeley Hammond <khammond@slack-corp.com> Co-authored-by: VerteDinde <vertedinde@electronjs.org> Co-authored-by: George Xu <33054982+georgexu99@users.noreply.github.com> Co-authored-by: George Xu <georgexu99@users.noreply.github.com> Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com> Co-authored-by: Robo <hop2deep@gmail.com> Co-authored-by: Jeremy Rose <jeremya@chromium.org> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
2022-11-17 19:59:23 +00:00
return extension.name !== 'Chromium PDF Viewer';
});
const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
const [, loadedExtension] = await loadedPromise;
const [, readyExtension] = await readyPromise;
2021-03-09 07:05:02 +00:00
expect(loadedExtension).to.deep.equal(extension);
expect(readyExtension).to.deep.equal(extension);
const unloadedPromise = once(customSession, 'extension-unloaded');
await customSession.removeExtension(extension.id);
const [, unloadedExtension] = await unloadedPromise;
2021-03-09 07:05:02 +00:00
expect(unloadedExtension).to.deep.equal(extension);
});
it('lists loaded extensions in getAllExtensions', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
expect(customSession.getAllExtensions()).to.deep.equal([e]);
customSession.removeExtension(e.id);
expect(customSession.getAllExtensions()).to.deep.equal([]);
});
it('gets an extension by id', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
expect(customSession.getExtension(e.id)).to.deep.equal(e);
});
it('confines an extension to the session it was loaded in', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
2019-11-01 20:37:02 +00:00
const w = new BrowserWindow({ show: false }); // not in the session
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('');
});
it('loading an extension in a temporary session throws an error', async () => {
const customSession = session.fromPartition(uuid.v4());
await expect(customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'))).to.eventually.be.rejectedWith('Extensions cannot be loaded in a temporary session');
});
describe('chrome.i18n', () => {
let w: BrowserWindow;
let extension: Extension;
const exec = async (name: string) => {
const p = once(ipcMain, 'success');
await w.webContents.executeJavaScript(`exec('${name}')`);
const [, result] = await p;
return result;
};
beforeEach(async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n', 'v2'));
w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
await w.loadURL(url);
});
it('getAcceptLanguages()', async () => {
const result = await exec('getAcceptLanguages');
chore: bump chromium to 100.0.4857.0 (main) (#32419) * chore: bump chromium in DEPS to 99.0.4819.0 * chore: update patches * chore: bump chromium in DEPS to 99.0.4824.0 * chore: update patches * chore: bump chromium in DEPS to 99.0.4827.0 * chore: update patches * 3352511: PiP: Add inkdrop and pointer cursor to PiP window buttons https://chromium-review.googlesource.com/c/chromium/src/+/3352511 * 3309164: webhid: Show FIDO devices in the chooser if allowed https://chromium-review.googlesource.com/c/chromium/src/+/3309164 * 3297868: hid: Add experimental HIDDevice.forget() https://chromium-review.googlesource.com/c/chromium/src/+/3297868 * 3362491: [Extensions] Move i18n API to //extensions https://chromium-review.googlesource.com/c/chromium/src/+/3362491 * MCC Refactor step0: Allow embedders to register associated_interface binders with RenderFrameHostImpl::associated_registry_. https://chromium-review.googlesource.com/c/chromium/src/+/3281481 * 3352616: [Gtk] Remove libgtk from the link-line https://chromium-review.googlesource.com/c/chromium/src/+/3352616 * 3249211: Clear-Site-Data support for partitioned cookies https://chromium-review.googlesource.com/c/chromium/src/+/3249211 * [Extensions][COIL] Use [allow|block]list in //extensions/common https://chromium-review.googlesource.com/c/chromium/src/+/3372668 * Begin ScopedUserPrefUpdate migration to modern base::Value https://chromium-review.googlesource.com/c/chromium/src/+/3376154 * [Code Health] Refactor PrefService GetDict + GetList to use base::Value https://chromium-review.googlesource.com/c/chromium/src/+/3343526 * 3354997: [CodeHealth] Remove deprecated SetDictionary method https://chromium-review.googlesource.com/c/chromium/src/+/3354997 * 3287323: Add LacrosPrefStore for lacros settings https://chromium-review.googlesource.com/c/chromium/src/+/3287323 * 3365916: [PA] Clean up remaining lazy commit code https://chromium-review.googlesource.com/c/chromium/src/+/3365916 * [MPArch] Target the external protocol error at the responsible frame. https://chromium-review.googlesource.com/c/chromium/src/+/3011560 * Pass origin to RegisterNonNetworkSubresourceURLLoaderFactories https://chromium-review.googlesource.com/c/chromium/src/+/3350608 * Linux: Send OSCrypt raw encryption key to the Network Service https://chromium-review.googlesource.com/c/chromium/src/+/3320484 * [PlzServiceWorker] Remove remaining references to PlzServiceWorker. https://chromium-review.googlesource.com/c/chromium/src/+/3359441 * chore: fixup for lint * 3327621: Fix tablet mode detection for Win 11. https://chromium-review.googlesource.com/c/chromium/src/+/3327621 * 3342428: ax_mac: move AXTextMarker conversion utils under ui umbrella https://chromium-review.googlesource.com/c/chromium/src/+/3342428 * 3353974: Mac: Use base::Feature for overlay features https://chromium-review.googlesource.com/c/chromium/src/+/3353974 * chore: bump chromium in DEPS to 99.0.4828.0 * chore: update patches * chore: bump chromium in DEPS to 99.0.4837.0 * chore: update patches * chore: update patches * 3379142: Drop FALLTHROUGH macro Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3379142 * 3381749: C++17: Allow use of std::map::try_emplace and std::map::insert_or_assign Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3381749 * chore: bump chromium in DEPS to 99.0.4839.0 * chore: update patches * chore: bump chromium in DEPS to 99.0.4840.0 * chore: bump chromium in DEPS to 99.0.4844.0 * 3395881: [api] Deprecate Local<v8::Context> v8::Object::CreationContext() Ref: https://chromium-review.googlesource.com/c/v8/v8/+/3395881 * chore: update patches * chore: bump chromium in DEPS to 100.0.4845.0 * chore: update patches * chore: bump chromium in DEPS to 100.0.4847.0 * chore: update patches * chore: bump chromium in DEPS to 100.0.4849.0 * chore: update patches * chore: bump chromium in DEPS to 100.0.4851.0 * chore: bump chromium in DEPS to 100.0.4853.0 * update patches * chore: update patches * update patches * 3383599: Fonts Access: Remove prototype that uses a font picker. https://chromium-review.googlesource.com/c/chromium/src/+/3383599 * 3404768: Remove ALLOW_UNUSED macros https://chromium-review.googlesource.com/c/chromium/src/+/3404768 * 3374762: Remove ignore_result.h https://chromium-review.googlesource.com/c/chromium/src/+/3374762 * 3399305: [unseasoned-pdf] Apply proper frame offsets for touch selections https://chromium-review.googlesource.com/c/chromium/src/+/3399305 * 3402210: [Extensions] Don't trigger unload event for already unloaded extension https://chromium-review.googlesource.com/c/chromium/src/+/3402210 * 3410912: Combine URLLoaderClient OnReceiveResponse and OnStartLoadingResponseBody. https://chromium-review.googlesource.com/c/chromium/src/+/3410912 * 3370428: Make the AuthSchemes policy support dynamic refresh https://chromium-review.googlesource.com/c/chromium/src/+/3370428 * 3407603: Finish ScopedUserPrefUpdate migration to modern base::Value https://chromium-review.googlesource.com/c/chromium/src/+/3407603 * 3378352: ozone/x11: move code from //ui/p/x11 to //ui/ozone/p/x11 https://chromium-review.googlesource.com/c/chromium/src/+/3378352 * 3370810: Delete chrome/service, AKA the Cloud Print service process. https://chromium-review.googlesource.com/c/chromium/src/+/3370810 * chore: bump chromium in DEPS to 100.0.4855.0 * chore: update patches * fixup! 3370810: Delete chrome/service, AKA the Cloud Print service process. * revert 3348007 to fix windows build * 3318572: [Code health] Fix gn check errors in //extensions/browser:* https://chromium-review.googlesource.com/c/chromium/src/+/3318572 * fix printing.patch * fix iwyu issue * 3408515: win: Make ShorcutOperation an enum class and modernize names https://chromium-review.googlesource.com/c/chromium/src/+/3408515 * 3388333: [UIA] Remove dead code accessibility_misc_utils.h/cc https://chromium-review.googlesource.com/c/chromium/src/+/3388333 * fix windows build? i hope * patch gn visibility of //ui/ozone/platform/x11 * missing include base/logging.h * use BUILDFLAG for USE_NSS_CERTS https://chromium-review.googlesource.com/c/chromium/src/+/3379123 * defined(OS_*) ==> BUILDFLAG(IS_*) https://bugs.chromium.org/p/chromium/issues/detail?id=1234043 * fixup! 3404768: Remove ALLOW_UNUSED macros * another attempt to fix windows build * temporarily disable the custom scheme service worker test https://github.com/electron/electron/issues/32664 * fix loading mv3 extensions not sure what cl broke this unfort. * fixup! 3404768: Remove ALLOW_UNUSED macros * patch nan https://chromium-review.googlesource.com/c/v8/v8/+/3395880 * fix node test * fix nullptr in FindPdfFrame * patch perfetto to fix build issue on win-ia32 https://source.chromium.org/chromium/_/android/platform/external/perfetto.git/+/bc44c3c7533c00e56f88c06c592d634aecc884be * fix build for linux-x64-testing-no-run-as-node * fix patch * skip <webview>.capturePage() test https://github.com/electron/electron/issues/32705 * test: fix failing tests of focus/blur events of WebContents (#32711) * inherit stdio from app module test child processes this prevents them from timing out due to full stdout buffers * test to see if we can get better logs on windows ci * try again for appveyor log things * skip contentTracing tests on ia32 * ci: disable gpu compositing * drop applied patch * fix merge fail * Revert "ci: disable gpu compositing" This reverts commit 0344129fcb19ea3e87e06c1110d751f22eba3fec. Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com> Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: John Kleinschmidt <jkleinsc@github.com> Co-authored-by: VerteDinde <khammond@slack-corp.com> Co-authored-by: VerteDinde <vertedinde@electronjs.org> Co-authored-by: Jeremy Rose <jeremya@chromium.org> Co-authored-by: Jeremy Rose <nornagon@nornagon.net> Co-authored-by: Cheng Zhao <zcbenz@gmail.com> Co-authored-by: deepak1556 <hop2deep@gmail.com>
2022-02-10 02:58:52 +00:00
expect(result).to.be.an('array').and.deep.equal(['en-US', 'en']);
});
it('getMessage()', async () => {
const result = await exec('getMessage');
expect(result.id).to.be.a('string').and.equal(extension.id);
expect(result.name).to.be.a('string').and.equal('chrome-i18n');
});
});
describe('chrome.runtime', () => {
let w: BrowserWindow;
const exec = async (name: string) => {
const p = once(ipcMain, 'success');
await w.webContents.executeJavaScript(`exec('${name}')`);
const [, result] = await p;
return result;
};
beforeEach(async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-runtime'));
w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
await w.loadURL(url);
});
it('getManifest()', async () => {
const result = await exec('getManifest');
expect(result).to.be.an('object').with.property('name', 'chrome-runtime');
});
it('id', async () => {
const result = await exec('id');
expect(result).to.be.a('string').with.lengthOf(32);
});
it('getURL()', async () => {
const result = await exec('getURL');
expect(result).to.be.a('string').and.match(/^chrome-extension:\/\/.*main.js$/);
});
it('getPlatformInfo()', async () => {
const result = await exec('getPlatformInfo');
expect(result).to.be.an('object');
expect(result.os).to.be.a('string');
expect(result.arch).to.be.a('string');
expect(result.nacl_arch).to.be.a('string');
});
});
describe('chrome.storage', () => {
it('stores and retrieves a key', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-storage'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
try {
const p = once(ipcMain, 'storage-success');
await w.loadURL(url);
const [, v] = await p;
expect(v).to.equal('value');
} finally {
w.destroy();
}
});
});
describe('chrome.webRequest', () => {
function fetch (contents: WebContents, url: string) {
return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`);
}
let customSession: Session;
let w: BrowserWindow;
beforeEach(() => {
customSession = session.fromPartition(`persist:${uuid.v4()}`);
w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true, contextIsolation: true } });
});
describe('onBeforeRequest', () => {
it('can cancel http requests', async () => {
await w.loadURL(url);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest'));
2021-01-28 19:51:08 +00:00
await expect(fetch(w.webContents, url)).to.eventually.be.rejectedWith('Failed to fetch');
});
it('does not cancel http requests when no extension loaded', async () => {
await w.loadURL(url);
2021-01-28 19:51:08 +00:00
await expect(fetch(w.webContents, url)).to.not.be.rejectedWith('Failed to fetch');
});
});
it('does not take precedence over Electron webRequest - http', async () => {
return new Promise<void>((resolve) => {
(async () => {
customSession.webRequest.onBeforeRequest((details, callback) => {
resolve();
callback({ cancel: true });
});
await w.loadURL(url);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest'));
fetch(w.webContents, url);
})();
});
});
it('does not take precedence over Electron webRequest - WebSocket', () => {
return new Promise<void>((resolve) => {
(async () => {
customSession.webRequest.onBeforeSendHeaders(() => {
resolve();
});
await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port: `${port}` } });
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss'));
})();
});
});
describe('WebSocket', () => {
it('can be proxied', async () => {
await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port: `${port}` } });
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss'));
customSession.webRequest.onSendHeaders((details) => {
if (details.url.startsWith('ws://')) {
expect(details.requestHeaders.foo).be.equal('bar');
}
});
});
});
});
describe('chrome.tabs', () => {
let customSession: Session;
before(async () => {
customSession = session.fromPartition(`persist:${uuid.v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
});
it('executeScript', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
await w.loadURL(url);
const message = { method: 'executeScript', args: ['1 + 2'] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [, , responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.equal(3);
});
it('connect', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
await w.loadURL(url);
const portName = uuid.v4();
const message = { method: 'connectTab', args: [portName] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = responseString.split(',');
expect(response[0]).to.equal(portName);
expect(response[1]).to.equal('howdy');
});
it('sendMessage receives the response', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
await w.loadURL(url);
const message = { method: 'sendMessage', args: ['Hello World!'] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response.message).to.equal('Hello World!');
expect(response.tabId).to.equal(w.webContents.id);
});
it('update', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
await w.loadURL(url);
const w2 = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w2.loadURL('about:blank');
const w2Navigated = once(w2.webContents, 'did-navigate');
const message = { method: 'update', args: [w2.webContents.id, { url }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
await w2Navigated;
expect(new URL(w2.getURL()).toString()).to.equal(new URL(url).toString());
expect(response.id).to.equal(w2.webContents.id);
});
});
describe('background pages', () => {
it('loads a lazy background page when sending a message', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
try {
w.loadURL(url);
const [, resp] = await once(ipcMain, 'bg-page-message-response');
expect(resp.message).to.deep.equal({ some: 'message' });
expect(resp.sender.id).to.be.a('string');
expect(resp.sender.origin).to.equal(url);
expect(resp.sender.url).to.equal(url + '/');
} finally {
w.destroy();
}
});
it('can use extension.getBackgroundPage from a ui page', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
expect(receivedMessage).to.deep.equal({ some: 'message' });
});
it('can use extension.getBackgroundPage from a ui page', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
expect(receivedMessage).to.deep.equal({ some: 'message' });
});
it('can use runtime.getBackgroundPage from a ui page', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(`chrome-extension://${id}/page-runtime-get-background.html`);
const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
expect(receivedMessage).to.deep.equal({ some: 'message' });
});
it('has session in background page', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
const [, bgPageContents] = await promise;
expect(bgPageContents.getType()).to.equal('backgroundPage');
await once(bgPageContents, 'did-finish-load');
expect(bgPageContents.getURL()).to.equal(`chrome-extension://${id}/_generated_background_page.html`);
expect(bgPageContents.session).to.not.equal(undefined);
});
it('can open devtools of background page', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
const [, bgPageContents] = await promise;
expect(bgPageContents.getType()).to.equal('backgroundPage');
bgPageContents.openDevTools();
bgPageContents.closeDevTools();
});
});
describe('devtools extensions', () => {
let showPanelTimeoutId: any = null;
afterEach(() => {
if (showPanelTimeoutId) clearTimeout(showPanelTimeoutId);
});
const showLastDevToolsPanel = (w: BrowserWindow) => {
w.webContents.once('devtools-opened', () => {
const show = () => {
if (w == null || w.isDestroyed()) return;
const { devToolsWebContents } = w as unknown as { devToolsWebContents: WebContents | undefined };
if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
return;
}
const showLastPanel = () => {
// this is executed in the devtools context, where UI is a global
const { EUI } = (window as any);
const instance = EUI.InspectorView.InspectorView.instance();
const tabs = instance.tabbedPane.tabs;
const lastPanelId = tabs[tabs.length - 1].id;
instance.showPanel(lastPanelId);
};
devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
showPanelTimeoutId = setTimeout(show, 100);
});
};
showPanelTimeoutId = setTimeout(show, 100);
});
};
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')('loads a devtools extension', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
customSession.loadExtension(path.join(fixtures, 'extensions', 'devtools-extension'));
const winningMessage = once(ipcMain, 'winning');
const w = new BrowserWindow({ show: true, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
await w.loadURL(url);
w.webContents.openDevTools();
showLastDevToolsPanel(w);
2020-05-26 14:25:57 +00:00
await winningMessage;
});
});
describe('chrome extension content scripts', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
const extensionPath = path.resolve(fixtures, 'extensions');
const addExtension = (name: string) => session.defaultSession.loadExtension(path.resolve(extensionPath, name));
const removeAllExtensions = () => {
Object.keys(session.defaultSession.getAllExtensions()).map(extName => {
session.defaultSession.removeExtension(extName);
});
};
let responseIdCounter = 0;
const executeJavaScriptInFrame = (webContents: WebContents, frameRoutingId: number, code: string) => {
return new Promise(resolve => {
const responseId = responseIdCounter++;
ipcMain.once(`executeJavaScriptInFrame_${responseId}`, (event, result) => {
resolve(result);
});
webContents.send('executeJavaScriptInFrame', frameRoutingId, code, responseId);
});
};
const generateTests = (sandboxEnabled: boolean, contextIsolationEnabled: boolean) => {
describe(`with sandbox ${sandboxEnabled ? 'enabled' : 'disabled'} and context isolation ${contextIsolationEnabled ? 'enabled' : 'disabled'}`, () => {
let w: BrowserWindow;
describe('supports "run_at" option', () => {
beforeEach(async () => {
await closeWindow(w);
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
contextIsolation: contextIsolationEnabled,
sandbox: sandboxEnabled
}
});
});
afterEach(async () => {
removeAllExtensions();
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should run content script at document_start', async () => {
await addExtension('content-script-document-start');
w.webContents.once('dom-ready', async () => {
const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(result).to.equal('red');
});
w.loadURL(url);
});
it('should run content script at document_idle', async () => {
await addExtension('content-script-document-idle');
w.loadURL(url);
const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor');
expect(result).to.equal('red');
});
it('should run content script at document_end', async () => {
await addExtension('content-script-document-end');
w.webContents.once('did-finish-load', async () => {
const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(result).to.equal('red');
});
w.loadURL(url);
});
});
describe('supports "all_frames" option', () => {
const contentScript = path.resolve(fixtures, 'extensions/content-script');
const contentPath = path.join(contentScript, 'frame-with-frame.html');
// Computed style values
const COLOR_RED = 'rgb(255, 0, 0)';
const COLOR_BLUE = 'rgb(0, 0, 255)';
const COLOR_TRANSPARENT = 'rgba(0, 0, 0, 0)';
let server: http.Server;
let port: number;
before(async () => {
server = http.createServer((_, res) => {
fs.readFile(contentPath, (error, content) => {
if (error) {
res.writeHead(500);
res.end(`Failed to load ${contentPath} : ${error.code}`);
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
});
({ port, url } = await listen(server));
session.defaultSession.loadExtension(contentScript);
});
after(() => {
session.defaultSession.removeExtension('content-script-test');
});
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
// enable content script injection in subframes
nodeIntegrationInSubFrames: true,
preload: path.join(contentScript, 'all_frames-preload.js')
}
});
});
afterEach(() =>
closeWindow(w).then(() => {
w = null as unknown as BrowserWindow;
})
);
it('applies matching rules in subframes', async () => {
const detailsPromise = emittedNTimes(w.webContents, 'did-frame-finish-load', 2);
w.loadURL(`http://127.0.0.1:${port}`);
const frameEvents = await detailsPromise;
await Promise.all(
frameEvents.map(async frameEvent => {
const [, isMainFrame, , frameRoutingId] = frameEvent;
const result: any = await executeJavaScriptInFrame(
w.webContents,
frameRoutingId,
`(() => {
const a = document.getElementById('all_frames_enabled')
const b = document.getElementById('all_frames_disabled')
return {
enabledColor: getComputedStyle(a).backgroundColor,
disabledColor: getComputedStyle(b).backgroundColor
}
})()`
);
expect(result.enabledColor).to.equal(COLOR_RED);
expect(result.disabledColor).to.equal(isMainFrame ? COLOR_BLUE : COLOR_TRANSPARENT);
})
);
});
});
});
};
2020-03-20 20:28:31 +00:00
generateTests(false, false);
generateTests(false, true);
generateTests(true, false);
generateTests(true, true);
});
describe('extension ui pages', () => {
afterEach(() => {
for (const e of session.defaultSession.getAllExtensions()) {
session.defaultSession.removeExtension(e.id);
}
});
it('loads a ui page of an extension', async () => {
const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
const w = new BrowserWindow({ show: false });
await w.loadURL(`chrome-extension://${id}/bare-page.html`);
const textContent = await w.webContents.executeJavaScript('document.body.textContent');
expect(textContent).to.equal('ui page loaded ok\n');
});
it('can load resources', async () => {
const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
const w = new BrowserWindow({ show: false });
await w.loadURL(`chrome-extension://${id}/page-script-load.html`);
const textContent = await w.webContents.executeJavaScript('document.body.textContent');
expect(textContent).to.equal('script loaded ok\n');
});
});
describe('manifest v3', () => {
it('registers background service worker', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const registrationPromise = new Promise<string>(resolve => {
customSession.serviceWorkers.once('registration-completed', (event, { scope }) => resolve(scope));
});
const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker'));
const scope = await registrationPromise;
expect(scope).equals(extension.url);
});
it('can run chrome extension APIs', async () => {
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker'));
await w.loadURL(url);
w.webContents.executeJavaScript('window.postMessage(\'fetch-confirmation\', \'*\')');
const [, , responseString] = await once(w.webContents, 'console-message');
const { message } = JSON.parse(responseString);
expect(message).to.equal('Hello from background.js');
});
describe('chrome.i18n', () => {
let customSession: Session;
let w = null as unknown as BrowserWindow;
before(async () => {
customSession = session.fromPartition(`persist:${uuid.v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n', 'v3'));
});
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
session: customSession,
nodeIntegration: true
}
});
});
afterEach(closeAllWindows);
it('getAcceptLanguages', async () => {
await w.loadURL(url);
const message = { method: 'getAcceptLanguages' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.be.an('array').that.is.not.empty('languages array is empty');
});
it('getUILanguage', async () => {
await w.loadURL(url);
const message = { method: 'getUILanguage' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.be.a('string');
});
it('getMessage', async () => {
await w.loadURL(url);
const message = { method: 'getMessage' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [, , responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.equal('Hola mundo!!');
});
it('detectLanguage', async () => {
await w.loadURL(url);
const greetings = [
'Ich liebe dich', // German
'Mahal kita', // Filipino
'愛してます', // Japanese
'دوستت دارم', // Persian
'Minä rakastan sinua' // Finnish
];
const message = { method: 'detectLanguage', args: [greetings] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [, , responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.be.an('array');
for (const item of response) {
expect(Object.keys(item)).to.deep.equal(['isReliable', 'languages']);
}
const languages = response.map((r: { isReliable: boolean, languages: any[] }) => r.languages[0]);
expect(languages).to.deep.equal([
{ language: 'de', percentage: 100 },
{ language: 'fil', percentage: 100 },
{ language: 'ja', percentage: 100 },
{ language: 'ps', percentage: 100 },
{ language: 'fi', percentage: 100 }
]);
});
});
describe('chrome.tabs', () => {
let customSession: Session;
let w = null as unknown as BrowserWindow;
before(async () => {
customSession = session.fromPartition(`persist:${uuid.v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-tabs', 'api-async'));
});
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
session: customSession
}
});
});
afterEach(closeAllWindows);
it('getZoom', async () => {
await w.loadURL(url);
const message = { method: 'getZoom' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.equal(1);
});
it('setZoom', async () => {
await w.loadURL(url);
const message = { method: 'setZoom', args: [2] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.deep.equal(2);
});
it('getZoomSettings', async () => {
await w.loadURL(url);
const message = { method: 'getZoomSettings' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.deep.equal({
defaultZoomFactor: 1,
mode: 'automatic',
scope: 'per-origin'
});
});
it('setZoomSettings', async () => {
await w.loadURL(url);
const message = { method: 'setZoomSettings', args: [{ mode: 'disabled' }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.deep.equal({
defaultZoomFactor: 1,
mode: 'disabled',
scope: 'per-tab'
});
});
describe('get', () => {
it('returns tab properties', async () => {
await w.loadURL(url);
const message = { method: 'get' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.have.property('url').that.is.a('string');
expect(response).to.have.property('title').that.is.a('string');
expect(response).to.have.property('active').that.is.a('boolean');
expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
expect(response).to.have.property('discarded').that.is.a('boolean');
expect(response).to.have.property('groupId').that.is.a('number');
expect(response).to.have.property('highlighted').that.is.a('boolean');
expect(response).to.have.property('id').that.is.a('number');
expect(response).to.have.property('incognito').that.is.a('boolean');
expect(response).to.have.property('index').that.is.a('number');
expect(response).to.have.property('pinned').that.is.a('boolean');
expect(response).to.have.property('selected').that.is.a('boolean');
expect(response).to.have.property('windowId').that.is.a('number');
});
it('does not return privileged properties without tabs permission', async () => {
const noPrivilegeSes = session.fromPartition(`persist:${uuid.v4()}`);
await noPrivilegeSes.loadExtension(path.join(fixtures, 'extensions', 'chrome-tabs', 'no-privileges'));
w = new BrowserWindow({ show: false, webPreferences: { session: noPrivilegeSes } });
await w.loadURL(url);
w.webContents.executeJavaScript('window.postMessage(\'{}\', \'*\')');
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).not.to.have.property('url');
expect(response).not.to.have.property('title');
expect(response).to.have.property('active').that.is.a('boolean');
expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
expect(response).to.have.property('discarded').that.is.a('boolean');
expect(response).to.have.property('groupId').that.is.a('number');
expect(response).to.have.property('highlighted').that.is.a('boolean');
expect(response).to.have.property('id').that.is.a('number');
expect(response).to.have.property('incognito').that.is.a('boolean');
expect(response).to.have.property('index').that.is.a('number');
expect(response).to.have.property('pinned').that.is.a('boolean');
expect(response).to.have.property('selected').that.is.a('boolean');
expect(response).to.have.property('windowId').that.is.a('number');
});
});
it('reload', async () => {
await w.loadURL(url);
const message = { method: 'reload' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const consoleMessage = once(w.webContents, 'console-message');
const finish = once(w.webContents, 'did-finish-load');
await Promise.all([consoleMessage, finish]).then(([[,, responseString]]) => {
const response = JSON.parse(responseString);
expect(response.status).to.equal('reloaded');
});
});
describe('update', () => {
it('can update muted status', async () => {
await w.loadURL(url);
const message = { method: 'update', args: [{ muted: true }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.have.property('mutedInfo').that.is.a('object');
const { mutedInfo } = response;
expect(mutedInfo).to.deep.eq({
muted: true,
reason: 'user'
});
});
it('fails when navigating to an invalid url', async () => {
await w.loadURL(url);
const message = { method: 'update', args: [{ url: 'chrome://crash' }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const { error } = JSON.parse(responseString);
expect(error).to.eq('I\'m sorry. I\'m afraid I can\'t do that.');
});
it('fails when navigating to prohibited url', async () => {
await w.loadURL(url);
const message = { method: 'update', args: [{ url: 'chrome://crash' }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const { error } = JSON.parse(responseString);
expect(error).to.eq('I\'m sorry. I\'m afraid I can\'t do that.');
});
it('fails when navigating to a devtools url without permission', async () => {
await w.loadURL(url);
const message = { method: 'update', args: [{ url: 'devtools://blah' }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [, , responseString] = await once(w.webContents, 'console-message');
const { error } = JSON.parse(responseString);
expect(error).to.eq('Cannot navigate to a devtools:// page without either the devtools or debugger permission.');
});
it('fails when navigating to a chrome-untrusted url', async () => {
await w.loadURL(url);
const message = { method: 'update', args: [{ url: 'chrome-untrusted://blah' }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [, , responseString] = await once(w.webContents, 'console-message');
const { error } = JSON.parse(responseString);
expect(error).to.eq('Cannot navigate to a chrome-untrusted:// page.');
});
it('fails when navigating to a file url withotut file access', async () => {
await w.loadURL(url);
const message = { method: 'update', args: [{ url: 'file://blah' }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [, , responseString] = await once(w.webContents, 'console-message');
const { error } = JSON.parse(responseString);
expect(error).to.eq('Cannot navigate to a file URL without local file access.');
});
});
describe('query', () => {
it('can query for a tab with specific properties', async () => {
await w.loadURL(url);
expect(w.webContents.isAudioMuted()).to.be.false('muted');
w.webContents.setAudioMuted(true);
expect(w.webContents.isAudioMuted()).to.be.true('not muted');
const message = { method: 'query', args: [{ muted: true }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [, , responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.have.lengthOf(1);
const tab = response[0];
expect(tab.mutedInfo).to.deep.equal({
muted: true,
reason: 'user'
});
});
it('only returns tabs in the same session', async () => {
await w.loadURL(url);
w.webContents.setAudioMuted(true);
const sameSessionWin = new BrowserWindow({
show: false,
webPreferences: {
session: customSession
}
});
sameSessionWin.webContents.setAudioMuted(true);
const newSession = session.fromPartition(`persist:${uuid.v4()}`);
const differentSessionWin = new BrowserWindow({
show: false,
webPreferences: {
session: newSession
}
});
differentSessionWin.webContents.setAudioMuted(true);
const message = { method: 'query', args: [{ muted: true }] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [, , responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.have.lengthOf(2);
for (const tab of response) {
expect(tab.mutedInfo).to.deep.equal({
muted: true,
reason: 'user'
});
}
});
});
});
describe('chrome.scripting', () => {
let customSession: Session;
let w = null as unknown as BrowserWindow;
before(async () => {
customSession = session.fromPartition(`persist:${uuid.v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-scripting'));
});
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
session: customSession,
nodeIntegration: true
}
});
});
afterEach(closeAllWindows);
it('executeScript', async () => {
await w.loadURL(url);
const message = { method: 'executeScript' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const updated = await once(w.webContents, 'page-title-updated');
expect(updated[1]).to.equal('HEY HEY HEY');
});
it('registerContentScripts', async () => {
await w.loadURL(url);
const message = { method: 'registerContentScripts' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.be.an('array').with.lengthOf(1);
expect(response[0]).to.deep.equal({
allFrames: false,
id: 'session-script',
js: ['content.js'],
matchOriginAsFallback: false,
matches: ['<all_urls>'],
persistAcrossSessions: false,
runAt: 'document_start',
world: 'ISOLATED'
});
});
it('insertCSS', async () => {
await w.loadURL(url);
const bgBefore = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).backgroundColor');
expect(bgBefore).to.equal('rgba(0, 0, 0, 0)');
const message = { method: 'insertCSS' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response.success).to.be.true();
const bgAfter = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).backgroundColor');
expect(bgAfter).to.equal('rgb(255, 0, 0)');
});
});
});
});