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: install playwright binding lazily (#35976)
Dmitry Gozmanbcd2f10dfdc1
diff --git a/packages/playwright-core/src/server/bidi/bidiBrowser.ts b/packages/playwright-core/src/server/bidi/bidiBrowser.tsindex d27a188c47..6781fa00c1 100644--- a/packages/playwright-core/src/server/bidi/bidiBrowser.ts+++ b/packages/playwright-core/src/server/bidi/bidiBrowser.ts@@ -20,8 +20,9 @@ import { BrowserContext, verifyGeolocation } from '../browserContext';import * as network from '../network';import { BidiConnection } from './bidiConnection';import { bidiBytesValueToString } from './bidiNetworkManager';-import { addMainBindingSource, BidiPage, kPlaywrightBindingChannel } from './bidiPage';+import { BidiPage, kPlaywrightBindingChannel } from './bidiPage';import { kUtilityInitScript } from '../page';+import { kPlaywrightBinding } from '../javascript';import * as bidi from './third_party/bidiProtocol';import type { RegisteredListener } from '../utils/eventsHelper';@@ -221,7 +222,6 @@ export class BidiBrowserContext extends BrowserContext {override async _initialize() {const promises: Promise<any>[] = [super._initialize(),- this._installMainBinding(),this._installUtilityScript(),];if (this._options.viewport) {@@ -239,22 +239,6 @@ export class BidiBrowserContext extends BrowserContext {await Promise.all(promises);}- // TODO: consider calling this only when bindings are added.- private async _installMainBinding() {- const args: bidi.Script.ChannelValue[] = [{- type: 'channel',- value: {- channel: kPlaywrightBindingChannel,- ownership: bidi.Script.ResultOwnership.Root,- }- }];- await this._browser._browserSession.send('script.addPreloadScript', {- functionDeclaration: addMainBindingSource,- arguments: args,- userContexts: [this._userContextId()],- });- }-private async _installUtilityScript() {await this._browser._browserSession.send('script.addPreloadScript', {functionDeclaration: `() => { return${kUtilityInitScript.source} }`,@@ -408,6 +392,21 @@ export class BidiBrowserContext extends BrowserContext {async doUpdateRequestInterception(): Promise<void> {}+ override async doExposePlaywrightBinding() {+ const args: bidi.Script.ChannelValue[] = [{+ type: 'channel',+ value: {+ channel: kPlaywrightBindingChannel,+ ownership: bidi.Script.ResultOwnership.Root,+ }+ }];+ await this._browser._browserSession.send('script.addPreloadScript', {+ functionDeclaration: `function addMainBinding(callback) { globalThis['${kPlaywrightBinding}'] = callback; }`,+ arguments: args,+ userContexts: [this._userContextId()],+ });+ }+onClosePersistent() {}override async clearCache(): Promise<void> {diff --git a/packages/playwright-core/src/server/bidi/bidiPage.ts b/packages/playwright-core/src/server/bidi/bidiPage.tsindex 9b5a671a6c..17d7c70d93 100644--- a/packages/playwright-core/src/server/bidi/bidiPage.ts+++ b/packages/playwright-core/src/server/bidi/bidiPage.ts@@ -19,7 +19,6 @@ import { eventsHelper } from '../utils/eventsHelper';import { BrowserContext } from '../browserContext';import * as dialog from '../dialog';import * as dom from '../dom';-import { kPlaywrightBinding } from '../javascript';import { Page } from '../page';import { BidiExecutionContext, createHandle } from './bidiExecutionContext';import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './bidiInput';@@ -544,9 +543,6 @@ export class BidiPage implements PageDelegate {}}-export const addMainBindingSource =- `function addMainBinding(callback) { globalThis['${kPlaywrightBinding}'] = callback; }`;-function toBidiExecutionContext(executionContext: dom.FrameExecutionContext): BidiExecutionContext {return executionContext.delegate as BidiExecutionContext;}diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.tsindex 4a2cd4bbca..b2f54eaec7 100644--- a/packages/playwright-core/src/server/browserContext.ts+++ b/packages/playwright-core/src/server/browserContext.ts@@ -96,6 +96,7 @@ export abstract class BrowserContext extends SdkObject {_closeReason: string | undefined;readonly clock: Clock;_clientCertificatesProxy: ClientCertificatesProxy | undefined;+ private _playwrightBindingExposed = false;constructor(browser: Browser, options: types.BrowserContextOptions, browserContextId: string | undefined) {super(browser, 'browser-context');@@ -283,6 +284,7 @@ export abstract class BrowserContext extends SdkObject {protected abstract doAddInitScript(initScript: InitScript): Promise<void>;protected abstract doRemoveNonInternalInitScripts(): Promise<void>;protected abstract doUpdateRequestInterception(): Promise<void>;+ protected abstract doExposePlaywrightBinding(): Promise<void>;protected abstract doClose(reason: string | undefined): Promise<void>;protected abstract onClosePersistent(): void;@@ -323,6 +325,17 @@ export abstract class BrowserContext extends SdkObject {return this._pageBindings.has(name);}+ async exposePlaywrightBindingIfNeeded() {+ if (this._playwrightBindingExposed)+ return;+ this._playwrightBindingExposed = true;+ await this.doExposePlaywrightBinding();+ }++ needsPlaywrightBinding() {+ return this._playwrightBindingExposed;+ }+async exposeBinding(name: string, needsHandle: boolean, playwrightBinding: frames.FunctionWithSource): Promise<void> {if (this._pageBindings.has(name))throw new Error(`Function "${name}" has been already registered`);@@ -330,6 +343,7 @@ export abstract class BrowserContext extends SdkObject {if (page.getBinding(name))throw new Error(`Function "${name}" has been already registered in one of the pages`);}+ await this.exposePlaywrightBindingIfNeeded();const binding = new PageBinding(name, playwrightBinding, needsHandle);this._pageBindings.set(name, binding);await this.doAddInitScript(binding.initScript);diff --git a/packages/playwright-core/src/server/chromium/crBrowser.ts b/packages/playwright-core/src/server/chromium/crBrowser.tsindex c1a894f9fa..3369c53fb7 100644--- a/packages/playwright-core/src/server/chromium/crBrowser.ts+++ b/packages/playwright-core/src/server/chromium/crBrowser.ts@@ -488,6 +488,11 @@ export class CRBrowserContext extends BrowserContext {await (sw as CRServiceWorker).updateRequestInterception();}+ override async doExposePlaywrightBinding() {+ for (const page of this._crPages())+ await page.exposePlaywrightBinding();+ }+async doClose(reason: string | undefined) {// Headful chrome cannot dispose browser context with opened 'beforeunload'// dialogs, so we should close all that are currently opened.diff --git a/packages/playwright-core/src/server/chromium/crPage.ts b/packages/playwright-core/src/server/chromium/crPage.tsindex f6f80f524e..bd36ae6941 100644--- a/packages/playwright-core/src/server/chromium/crPage.ts+++ b/packages/playwright-core/src/server/chromium/crPage.ts@@ -234,6 +234,10 @@ export class CRPage implements PageDelegate {await this._forAllFrameSessions(frame => frame._evaluateOnNewDocument(initScript, world));}+ async exposePlaywrightBinding() {+ await this._forAllFrameSessions(frame => frame.exposePlaywrightBinding());+ }+async removeNonInternalInitScripts() {await this._forAllFrameSessions(frame => frame._removeEvaluatesOnNewDocument());}@@ -506,7 +510,6 @@ class FrameSession {this._client.send('Log.enable', {}),lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', { enabled: true }),this._client.send('Runtime.enable', {}),- this._client.send('Runtime.addBinding', { name: kPlaywrightBinding }),this._client.send('Page.addScriptToEvaluateOnNewDocument', {source: '',worldName: UTILITY_WORLD_NAME,@@ -515,6 +518,8 @@ class FrameSession {this._client.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }),];if (!isSettingStorageState) {+ if (this._crPage._browserContext.needsPlaywrightBinding())+ promises.push(this.exposePlaywrightBinding());if (this._isMainFrame())promises.push(this._client.send('Emulation.setFocusEmulationEnabled', { enabled: true }));const options = this._crPage._browserContext._options;@@ -1062,6 +1067,10 @@ class FrameSession {await Promise.all(identifiers.map(identifier => this._client.send('Page.removeScriptToEvaluateOnNewDocument', { identifier })));}+ async exposePlaywrightBinding() {+ await this._client.send('Runtime.addBinding', { name: kPlaywrightBinding });+ }+async _getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null> {const nodeInfo = await this._client.send('DOM.describeNode', {objectId: handle._objectIddiff --git a/packages/playwright-core/src/server/firefox/ffBrowser.ts b/packages/playwright-core/src/server/firefox/ffBrowser.tsindex fafde3d2fe..f48cdeff30 100644--- a/packages/playwright-core/src/server/firefox/ffBrowser.ts+++ b/packages/playwright-core/src/server/firefox/ffBrowser.ts@@ -185,7 +185,6 @@ export class FFBrowserContext extends BrowserContext {const browserContextId = this._browserContextId;const promises: Promise<any>[] = [super._initialize(),- this._browser.session.send('Browser.addBinding', { browserContextId: this._browserContextId, name: kPlaywrightBinding, script: '' }),this._updateInitScripts(),];if (this._options.acceptDownloads !== 'internal-browser-default') {@@ -392,6 +391,10 @@ export class FFBrowserContext extends BrowserContext {]);}+ override async doExposePlaywrightBinding() {+ this._browser.session.send('Browser.addBinding', { browserContextId: this._browserContextId, name: kPlaywrightBinding, script: '' });+ }+onClosePersistent() {}override async clearCache(): Promise<void> {diff --git a/packages/playwright-core/src/server/page.ts b/packages/playwright-core/src/server/page.tsindex e9d676bed8..70f2d1b3c2 100644--- a/packages/playwright-core/src/server/page.ts+++ b/packages/playwright-core/src/server/page.ts@@ -344,6 +344,7 @@ export class Page extends SdkObject {throw new Error(`Function "${name}" has been already registered`);if (this.browserContext._pageBindings.has(name))throw new Error(`Function "${name}" has been already registered in the browser context`);+ await this.browserContext.exposePlaywrightBindingIfNeeded();const binding = new PageBinding(name, playwrightBinding, needsHandle);this._pageBindings.set(name, binding);await this.delegate.addInitScript(binding.initScript);diff --git a/packages/playwright-core/src/server/webkit/wkBrowser.ts b/packages/playwright-core/src/server/webkit/wkBrowser.tsindex 537d898c0c..0ccc9b4791 100644--- a/packages/playwright-core/src/server/webkit/wkBrowser.ts+++ b/packages/playwright-core/src/server/webkit/wkBrowser.ts@@ -329,6 +329,11 @@ export class WKBrowserContext extends BrowserContext {await (page.delegate as WKPage).updateRequestInterception();}+ override async doExposePlaywrightBinding() {+ for (const page of this.pages())+ await (page.delegate as WKPage).exposePlaywrightBinding();+ }+onClosePersistent() {}override async clearCache(): Promise<void> {diff --git a/packages/playwright-core/src/server/webkit/wkPage.ts b/packages/playwright-core/src/server/webkit/wkPage.tsindex cbaf7b57fd..b15f313141 100644--- a/packages/playwright-core/src/server/webkit/wkPage.ts+++ b/packages/playwright-core/src/server/webkit/wkPage.ts@@ -176,12 +176,13 @@ export class WKPage implements PageDelegate {const promises: Promise<any>[] = [// Resource tree should be received before first execution context.session.send('Runtime.enable'),- session.send('Runtime.addBinding', { name: kPlaywrightBinding }),session.send('Page.createUserWorld', { name: UTILITY_WORLD_NAME }).catch(_ => {}), // Worlds are per-processsession.send('Console.enable'),session.send('Network.enable'),this._workers.initializeSession(session)];+ if (this._page.browserContext.needsPlaywrightBinding())+ promises.push(session.send('Runtime.addBinding', { name: kPlaywrightBinding }));if (this._page.needsRequestInterception()) {promises.push(session.send('Network.setInterceptionEnabled', { enabled: true }));promises.push(session.send('Network.setResourceCachingDisabled', { disabled: true }));@@ -772,6 +773,10 @@ export class WKPage implements PageDelegate {await this._updateBootstrapScript();}+ async exposePlaywrightBinding() {+ await this._updateState('Runtime.addBinding', { name: kPlaywrightBinding });+ }+private _calculateBootstrapScript(): string {const scripts: string[] = [];if (!this._page.browserContext._options.isMobile) {