Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: snapshot main-world globals for no-utility-world contexts (#40971)
Pavel Feldmanb4d80760f3cd
diff --git a/packages/playwright-core/src/server/dom.ts b/packages/playwright-core/src/server/dom.tsindex bd0f24e8cc..4ff97881eb 100644--- a/packages/playwright-core/src/server/dom.ts+++ b/packages/playwright-core/src/server/dom.ts@@ -54,7 +54,7 @@ export class FrameExecutionContext extends js.ExecutionContext {readonly world: types.World | null;constructor(delegate: js.ExecutionContextDelegate, frame: frames.Frame, world: types.World|null) {- super(frame, delegate, world || 'content-script');+ super(frame, delegate, world || 'content-script', { noUtilityWorld: frame._page.delegate.noUtilityWorld?.() });this.frame = frame;this.world = world;}@@ -98,8 +98,10 @@ export class FrameExecutionContext extends js.ExecutionContext {isUtilityWorld: this.world === 'utility',customEngines,};+ const globalsSnapshot = this.frame._page.delegate.noUtilityWorld?.() ? js.mainWorldGlobalsSnapshotSource : '';const source = `(() => {+ ${globalsSnapshot}const module = {};${rawInjectedScriptSource.source}return new (module.exports.InjectedScript())(globalThis, ${JSON.stringify(options)});diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.tsindex 3ec2330453..92f3113f26 100644--- a/packages/playwright-core/src/server/frames.ts+++ b/packages/playwright-core/src/server/frames.ts@@ -23,6 +23,7 @@ import { asLocator } from '@isomorphic/locatorGenerators';import { assert } from '@isomorphic/assert';import { constructURLBasedOnBaseURL } from '@isomorphic/urlMatch';import { makeWaitForNextTask } from '@utils/task';+import { createGuid } from '@utils/crypto';import { BrowserContext } from './browserContext';import * as dom from './dom';import { TimeoutError } from './errors';@@ -475,7 +476,6 @@ export class Frame extends SdkObject<FrameEventMap> {_name = '';_inflightRequests = new Set<network.Request>();private _networkIdleTimer: NodeJS.Timeout | undefined;- private _setContentCounter = 0;readonly _detachedScope = new LongStandingScope();private _raceAgainstEvaluationStallingEventsPromises = new Set<ManualPromise<any>>();readonly _redirectedNavigations = new Map<string, { url: string, gotoPromise: Promise<network.Response | null> }>(); // documentId -> data@@ -735,6 +735,8 @@ export class Frame extends SdkObject<FrameEventMap> {}context(world: types.World): Promise<dom.FrameExecutionContext> {+ if (this._page.delegate.noUtilityWorld?.())+ world = 'main';return this._contextData.get(world)!.contextPromise.then(contextOrDestroyedReason => {if (contextOrDestroyedReason instanceof js.ExecutionContext)return contextOrDestroyedReason;@@ -919,7 +921,7 @@ export class Frame extends SdkObject<FrameEventMap> {}async setContent(progress: Progress, html: string, options: types.NavigateOptions): Promise<void> {- const tag = `--playwright--set--content--${this._id}--${++this._setContentCounter}--`;+ const tag = `--playwright--set--content--${createGuid()}--`;await this.raceNavigationAction(progress, async () => {const waitUntil = options.waitUntil === undefined ? 'load' : options.waitUntil;progress.log(`setting frame content, waiting until "${waitUntil}"`);diff --git a/packages/playwright-core/src/server/javascript.ts b/packages/playwright-core/src/server/javascript.tsindex 878964f9be..20b247e31a 100644--- a/packages/playwright-core/src/server/javascript.ts+++ b/packages/playwright-core/src/server/javascript.ts@@ -60,10 +60,12 @@ export class ExecutionContext extends SdkObject {private _utilityScriptPromise: Promise<JSHandle> | undefined;private _contextDestroyedScope = new LongStandingScope();readonly worldNameForTest: string;+ private _noUtilityWorld: boolean | undefined;- constructor(parent: SdkObject, delegate: ExecutionContextDelegate, worldNameForTest: string) {+ constructor(parent: SdkObject, delegate: ExecutionContextDelegate, worldNameForTest: string, options?: { noUtilityWorld?: boolean }) {super(parent, 'execution-context');this.worldNameForTest = worldNameForTest;+ this._noUtilityWorld = options?.noUtilityWorld;this.delegate = delegate;}@@ -102,8 +104,10 @@ export class ExecutionContext extends SdkObject {private _utilityScript(): Promise<JSHandle<UtilityScript>> {if (!this._utilityScriptPromise) {+ const globalsSnapshot = this._noUtilityWorld ? mainWorldGlobalsSnapshotSource : '';const source = `(() => {+ ${globalsSnapshot}const module = {};${rawUtilityScriptSource.source}return new (module.exports.UtilityScript())(globalThis, ${isUnderTest()});@@ -357,3 +361,28 @@ export function sparseArrayToString(entries: { name: string, value?: any }[]): sreturn '[' + tokens.join(', ') + ']';}++// Builtins that are frequently replaced or polyfilled by libraries (Prototype.js, MooTools,+// core-js, es6-shim, Sentry/Bugsnag, XRegExp, Web Components / Promise polyfills, etc.).+// Snapshotting the constructor reference protects the injected bundle from those overrides.+const snapshottedFunctionBuiltins = [+ // DOM+ 'Node', 'Element', 'NodeFilter', 'HTMLElement', 'Document', 'ShadowRoot',+ 'MutationObserver', 'Event', 'CustomEvent', 'EventTarget',+ // JS standard+ 'Map', 'Set', 'WeakMap', 'WeakSet', 'Promise', 'Symbol',+ 'Error', 'TypeError', 'RegExp', 'Array', 'Object',+];++// Non-callable globals (objects) — Prototype.js historically replaced JSON.+const snapshottedObjectBuiltins = ['JSON', 'Math'];++export const saveGlobalsSnapshotSource = `window.__pwSnapshotGlobals = {+${[...snapshottedFunctionBuiltins, ...snapshottedObjectBuiltins].map(n => ` ${n}: window.${n}`).join(',\n')}+};`;++export const mainWorldGlobalsSnapshotSource = `+ const __snap = globalThis.__pwSnapshotGlobals || {};+${snapshottedFunctionBuiltins.map(n => ` const ${n} = (typeof globalThis.${n} === 'function' ? globalThis.${n} : __snap.${n});`).join('\n')}+${snapshottedObjectBuiltins.map(n => ` const ${n} = (typeof globalThis.${n} === 'object' && globalThis.${n} ? globalThis.${n} : __snap.${n});`).join('\n')}+`;diff --git a/packages/playwright-core/src/server/page.ts b/packages/playwright-core/src/server/page.tsindex 898adbade9..aa8429d37c 100644--- a/packages/playwright-core/src/server/page.ts+++ b/packages/playwright-core/src/server/page.ts@@ -40,6 +40,7 @@ import * as rawBindingsControllerSource from '../generated/bindingsControllerSouimport { Overlay } from './overlay';import { NonRecoverableDOMError } from './dom';import { Screencast } from './screencast';+import { saveGlobalsSnapshotSource } from './javascript';import type { Artifact } from './artifact';import type { BrowserContextEventMap } from './browserContext';@@ -92,6 +93,7 @@ export interface PageDelegate {pdf?: (options: channels.PagePdfParams) => Promise<Buffer>;coverage?: () => any;+ noUtilityWorld?: () => boolean;// Work around WebKit's raf issues on Windows.rafCountForStablePosition(): number;@@ -220,6 +222,10 @@ export class Page extends SdkObject<PageEventMap> {}async reportAsNew(opener: Page | undefined, error?: Error) {+ if (this.delegate.noUtilityWorld?.()) {+ await this._addInitScript(saveGlobalsSnapshotSource);+ await this.safeNonStallingEvaluateInAllFrames(saveGlobalsSnapshotSource, 'main');+ }if (opener) {const openerPageOrError = await opener.waitForInitializedOrError();if (openerPageOrError instanceof Page && !openerPageOrError.isClosed())