How to use pushInitScripts method in Playwright Internal

Best JavaScript code snippet using playwright-internal

TargetRegistry.js

Source:TargetRegistry.js Github

copy

Full Screen

...452 await this._channel.connect('').send('ensurePermissions', {}).catch(e => void e);453 }454 async setInitScripts(scripts) {455 this._pageInitScripts = scripts;456 await this.pushInitScripts();457 }458 async pushInitScripts() {459 await this._channel.connect('').send('setInitScripts', [...this._browserContext.initScripts, ...this._pageInitScripts]).catch(e => void e);460 }461 async addBinding(worldName, name, script) {462 await this._channel.connect('').send('addBinding', { worldName, name, script }).catch(e => void e);463 }464 async applyContextSetting(name, value) {465 await this._channel.connect('').send('applyContextSetting', { name, value }).catch(e => void e);466 }467 async hasFailedToOverrideTimezone() {468 return await this._channel.connect('').send('hasFailedToOverrideTimezone').catch(e => true);469 }470 async _startVideoRecording({width, height, dir}) {471 // On Mac the window may not yet be visible when TargetCreated and its472 // NSWindow.windowNumber may be -1, so we wait until the window is known473 // to be initialized and visible.474 await this.windowReady();475 const file = OS.Path.join(dir, helper.generateId() + '.webm');476 if (width < 10 || width > 10000 || height < 10 || height > 10000)477 throw new Error("Invalid size");478 const docShell = this._gBrowser.ownerGlobal.docShell;479 // Exclude address bar and navigation control from the video.480 const rect = this.linkedBrowser().getBoundingClientRect();481 const devicePixelRatio = this._window.devicePixelRatio;482 let sessionId;483 const registry = this._registry;484 const screencastClient = {485 QueryInterface: ChromeUtils.generateQI([Ci.nsIScreencastServiceClient]),486 screencastFrame(data, deviceWidth, deviceHeight) {487 },488 screencastStopped() {489 registry.emit(TargetRegistry.Events.ScreencastStopped, sessionId);490 },491 };492 const viewport = this._viewportSize || this._browserContext.defaultViewportSize || { width: 0, height: 0 };493 sessionId = screencastService.startVideoRecording(screencastClient, docShell, true, file, width, height, 0, viewport.width, viewport.height, devicePixelRatio * rect.top);494 this._videoRecordingInfo = { sessionId, file };495 this.emit(PageTarget.Events.ScreencastStarted);496 }497 _stopVideoRecording() {498 if (!this._videoRecordingInfo)499 throw new Error('No video recording in progress');500 const videoRecordingInfo = this._videoRecordingInfo;501 this._videoRecordingInfo = undefined;502 screencastService.stopVideoRecording(videoRecordingInfo.sessionId);503 }504 videoRecordingInfo() {505 return this._videoRecordingInfo;506 }507 async startScreencast({ width, height, quality }) {508 // On Mac the window may not yet be visible when TargetCreated and its509 // NSWindow.windowNumber may be -1, so we wait until the window is known510 // to be initialized and visible.511 await this.windowReady();512 if (width < 10 || width > 10000 || height < 10 || height > 10000)513 throw new Error("Invalid size");514 const docShell = this._gBrowser.ownerGlobal.docShell;515 // Exclude address bar and navigation control from the video.516 const rect = this.linkedBrowser().getBoundingClientRect();517 const devicePixelRatio = this._window.devicePixelRatio;518 const self = this;519 const screencastClient = {520 QueryInterface: ChromeUtils.generateQI([Ci.nsIScreencastServiceClient]),521 screencastFrame(data, deviceWidth, deviceHeight) {522 if (self._screencastRecordingInfo)523 self.emit(PageTarget.Events.ScreencastFrame, { data, deviceWidth, deviceHeight });524 },525 screencastStopped() {526 },527 };528 const viewport = this._viewportSize || this._browserContext.defaultViewportSize || { width: 0, height: 0 };529 const screencastId = screencastService.startVideoRecording(screencastClient, docShell, false, '', width, height, quality || 90, viewport.width, viewport.height, devicePixelRatio * rect.top);530 this._screencastRecordingInfo = { screencastId };531 return { screencastId };532 }533 screencastFrameAck({ screencastId }) {534 if (!this._screencastRecordingInfo || this._screencastRecordingInfo.screencastId !== screencastId)535 return;536 screencastService.screencastFrameAck(screencastId);537 }538 stopScreencast() {539 if (!this._screencastRecordingInfo)540 throw new Error('No screencast in progress');541 const { screencastId } = this._screencastRecordingInfo;542 this._screencastRecordingInfo = undefined;543 screencastService.stopVideoRecording(screencastId);544 }545 dispose() {546 this._disposed = true;547 if (this._videoRecordingInfo)548 this._stopVideoRecording();549 if (this._screencastRecordingInfo)550 this.stopScreencast();551 this._browserContext.pages.delete(this);552 this._registry._browserToTarget.delete(this._linkedBrowser);553 this._registry._browserBrowsingContextToTarget.delete(this._linkedBrowser.browsingContext);554 try {555 helper.removeListeners(this._eventListeners);556 } catch (e) {557 // In some cases, removing listeners from this._linkedBrowser fails558 // because it is already half-destroyed.559 if (e)560 dump(e.message + '\n' + e.stack + '\n');561 }562 this._registry.emit(TargetRegistry.Events.TargetDestroyed, this);563 }564}565PageTarget.Events = {566 ScreencastStarted: Symbol('PageTarget.ScreencastStarted'),567 ScreencastFrame: Symbol('PageTarget.ScreencastFrame'),568 Crashed: Symbol('PageTarget.Crashed'),569 DialogOpened: Symbol('PageTarget.DialogOpened'),570 DialogClosed: Symbol('PageTarget.DialogClosed'),571};572function fromProtocolColorScheme(colorScheme) {573 if (colorScheme === 'light' || colorScheme === 'dark')574 return colorScheme;575 if (colorScheme === null || colorScheme === 'no-preference')576 return undefined;577 throw new Error('Unknown color scheme: ' + colorScheme);578}579function fromProtocolReducedMotion(reducedMotion) {580 if (reducedMotion === 'reduce' || reducedMotion === 'no-preference')581 return reducedMotion;582 if (reducedMotion === null)583 return undefined;584 throw new Error('Unknown reduced motion: ' + reducedMotion);585}586function fromProtocolForcedColors(forcedColors) {587 if (forcedColors === 'active' || forcedColors === 'none')588 return forcedColors;589 if (forcedColors === null)590 return undefined;591 throw new Error('Unknown forced colors: ' + forcedColors);592}593class BrowserContext {594 constructor(registry, browserContextId, removeOnDetach) {595 this._registry = registry;596 this.browserContextId = browserContextId;597 // Default context has userContextId === 0, but we pass undefined to many APIs just in case.598 this.userContextId = 0;599 if (browserContextId !== undefined) {600 const identity = ContextualIdentityService.create(IDENTITY_NAME + browserContextId);601 this.userContextId = identity.userContextId;602 }603 this._principals = [];604 // Maps origins to the permission lists.605 this._permissions = new Map();606 this._registry._browserContextIdToBrowserContext.set(this.browserContextId, this);607 this._registry._userContextIdToBrowserContext.set(this.userContextId, this);608 this._proxy = null;609 this.removeOnDetach = removeOnDetach;610 this.extraHTTPHeaders = undefined;611 this.httpCredentials = undefined;612 this.requestInterceptionEnabled = undefined;613 this.ignoreHTTPSErrors = undefined;614 this.downloadOptions = undefined;615 this.defaultViewportSize = undefined;616 this.deviceScaleFactor = undefined;617 this.defaultUserAgent = null;618 this.defaultPlatform = null;619 this.javaScriptDisabled = false;620 this.touchOverride = false;621 this.colorScheme = 'none';622 this.forcedColors = 'no-override';623 this.reducedMotion = 'none';624 this.videoRecordingOptions = undefined;625 this.initScripts = [];626 this.bindings = [];627 this.settings = {};628 this.pages = new Set();629 }630 setColorScheme(colorScheme) {631 this.colorScheme = fromProtocolColorScheme(colorScheme);632 for (const page of this.pages)633 page.updateColorSchemeOverride();634 }635 setReducedMotion(reducedMotion) {636 this.reducedMotion = fromProtocolReducedMotion(reducedMotion);637 for (const page of this.pages)638 page.updateReducedMotionOverride();639 }640 setForcedColors(forcedColors) {641 this.forcedColors = fromProtocolForcedColors(forcedColors);642 for (const page of this.pages)643 page.updateForcedColorsOverride();644 }645 async destroy() {646 if (this.userContextId !== 0) {647 ContextualIdentityService.remove(this.userContextId);648 for (const page of this.pages)649 page.close();650 if (this.pages.size) {651 await new Promise(f => {652 const listener = helper.on(this._registry, TargetRegistry.Events.TargetDestroyed, () => {653 if (!this.pages.size) {654 helper.removeListeners([listener]);655 f();656 }657 });658 });659 }660 }661 this._registry._browserContextIdToBrowserContext.delete(this.browserContextId);662 this._registry._userContextIdToBrowserContext.delete(this.userContextId);663 }664 setProxy(proxy) {665 // Clear AuthCache.666 Services.obs.notifyObservers(null, "net:clear-active-logins");667 this._proxy = proxy;668 }669 setIgnoreHTTPSErrors(ignoreHTTPSErrors) {670 if (this.ignoreHTTPSErrors === ignoreHTTPSErrors)671 return;672 this.ignoreHTTPSErrors = ignoreHTTPSErrors;673 const certOverrideService = Cc[674 "@mozilla.org/security/certoverride;1"675 ].getService(Ci.nsICertOverrideService);676 if (ignoreHTTPSErrors) {677 Preferences.set("network.stricttransportsecurity.preloadlist", false);678 Preferences.set("security.cert_pinning.enforcement_level", 0);679 certOverrideService.setDisableAllSecurityChecksAndLetAttackersInterceptMyData(true, this.userContextId);680 } else {681 certOverrideService.setDisableAllSecurityChecksAndLetAttackersInterceptMyData(false, this.userContextId);682 }683 }684 setDefaultUserAgent(userAgent) {685 this.defaultUserAgent = userAgent;686 for (const page of this.pages)687 page.updateUserAgent();688 }689 setDefaultPlatform(platform) {690 this.defaultPlatform = platform;691 for (const page of this.pages)692 page.updatePlatform();693 }694 setJavaScriptDisabled(javaScriptDisabled) {695 this.javaScriptDisabled = javaScriptDisabled;696 for (const page of this.pages)697 page.updateJavaScriptDisabled();698 }699 setTouchOverride(touchOverride) {700 this.touchOverride = touchOverride;701 for (const page of this.pages)702 page.updateTouchOverride();703 }704 async setDefaultViewport(viewport) {705 this.defaultViewportSize = viewport ? viewport.viewportSize : undefined;706 this.deviceScaleFactor = viewport ? viewport.deviceScaleFactor : undefined;707 await Promise.all(Array.from(this.pages).map(page => page.updateViewportSize()));708 }709 async setInitScripts(scripts) {710 this.initScripts = scripts;711 await Promise.all(Array.from(this.pages).map(page => page.pushInitScripts()));712 }713 async addBinding(worldName, name, script) {714 this.bindings.push({ worldName, name, script });715 await Promise.all(Array.from(this.pages).map(page => page.addBinding(worldName, name, script)));716 }717 async applySetting(name, value) {718 this.settings[name] = value;719 await Promise.all(Array.from(this.pages).map(page => page.applyContextSetting(name, value)));720 }721 async grantPermissions(origin, permissions) {722 this._permissions.set(origin, permissions);723 const promises = [];724 for (const page of this.pages) {725 if (origin === '*' || page._url.startsWith(origin)) {...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const path = require('path');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.evaluate(() => {8 window.playwright = require('playwright');9 window.playwright.chromium.pushInitScript(10 path.join(__dirname, 'test.js')11 );12 });13 await page.evaluate(() => {14 console.log('Hello from the browser');15 console.log('Hello from the browser');16 });17 await browser.close();18})();19console.log('Hello from the browser');20console.log('Hello from the browser');

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.evaluate(() => {7 window.__playwright__internal__pushInitScript(() => {8 window.initScript = () => console.log('init script was called');9 });10 });11 await page.evaluate(() => {12 console.log('initScript' in window);13 });14 await page.evaluate(() => {15 window.initScript();16 });17 await browser.close();18})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch({ headless: false });4 const context = await browser.newContext();5 await context.pushInitScript({ content: 'window.__foo = "bar";' });6 const page = await context.newPage();7 const foo = await page.evaluate(() => window.__foo);8 console.log('foo', foo);9 await browser.close();10})();11const playwright = require('playwright');12(async () => {13 const browser = await playwright.chromium.launch({ headless: false });14 const context = await browser.newContext();15 await context.pushInitScript({ content: () => window.__foo = "bar" });16 const page = await context.newPage();17 const foo = await page.evaluate(() => window.__foo);18 console.log('foo', foo);19 await browser.close();20})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2const { pushInitScripts } = require('playwright/lib/server/browserContext');3const browser = await playwright.chromium.launch();4const context = await browser.newContext();5pushInitScripts(context, [6 { path: require.resolve('playwright/lib/server/injected/instrumentation.js') },7 { path: require.resolve('playwright/lib/server/injected/recorderApp.js') },8 { path: require.resolve('playwright/lib/server/injected/recorderAppWorker.js') },9 { path: require.resolve('playwright/lib/server/injected/recorderAppWorker.js') },10 { path: require.resolve('playwright/lib/server/injected/recorderAppWorker.js') },11 { path: require.resolve('playwright/lib/server/injected/recorderAppWorker.js') },12 { path: require.resolve('playwright/lib/server/injected/recorderAppWorker.js') },13 { path: require.resolve('playwright/lib/server/injected/recorderAppWorker.js') },14 { path: require.resolve('playwright/lib/server/injected/recorderAppWorker.js') }15]);16const page = await context.newPage();17await page.click('text=example');18await page.close();19await context.close();20await browser.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require("playwright");2const { pushInitScript } = require("playwright/lib/server/browserContext");3const { chromium } = require("playwright");4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 pushInitScript(context, `window.test = 'hello'`);8 const page = await context.newPage();9 await page.pause();10 await browser.close();11})();12const playwright = require("playwright");13const { chromium } = require("playwright");14describe("Playwright Internal API", () => {15 it("should use pushInitScripts method of Playwright Internal API", async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 await context.addInitScript(`window.test = 'hello'`);19 const page = await context.newPage();20 await page.pause();21 await browser.close();22 });23});24const playwright = require("playwright");25const { chromium } = require("playwright");26describe("Playwright Internal API", () => {27 it("should use pushInitScripts method of Playwright Internal API", async () => {28 const browser = await chromium.launch();29 const context = await browser.newContext();30 await context.addInitScript(`window.test = 'hello'`);31 const page = await context.newPage();32 await page.pause();33 await browser.close();34 });35});36const playwright = require("playwright");37const { chromium } = require("playwright");38describe("Playwright Internal API", () => {39 it("should use pushInitScripts method of Playwright Internal API", async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();42 await context.addInitScript(`window.test = 'hello'`);43 const page = await context.newPage();44 await page.pause();45 await browser.close();46 });47});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { pushInitScripts } = require('playwright-core/lib/client/initScript');2const playwright = require('playwright-core');3(async () => {4 const browser = await playwright.chromium.launch({5 });6 const page = await browser.newPage();7 await browser.close();8})();9pushInitScripts('chromium', async (context, options) => {10 await context.addInitScript(() => {11 window.customFunction = (a, b) => a + b;12 });13});14const { chromium } = require('playwright');15const playwright = require('playwright-core');16(async () => {17 const browser = await playwright.chromium.launch({18 });19 const page = await browser.newPage();20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch({25 });26 const page = await browser.newPage();27 await browser.close();28})();29const playwright = require('playwright-core');30(async () => {31 const browser = await playwright.chromium.launch({32 });33 const page = await browser.newPage();34 await browser.close();35})();36const playwright = require('playwright-core');37const { chromium } = playwright;38(async () => {39 const browser = await playwright.chromium.launch({40 });41 const page = await browser.newPage();42 await browser.close();43})();44const playwright = require('playwright-core');45const { chromium } = playwright;46(async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { pushInitScript } = require('playwright/lib/server/browserContext');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 await pushInitScript(context, () => {7 window.foo = 'bar';8 });9 const page = await context.newPage();10 console.log(await page.evaluate(() => window.foo));11 await browser.close();12})();13const { chromium } = require('playwright');14const { pushInitScript } = require('playwright/lib/server/browserContext');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 await pushInitScript(context, () => {19 window.foo = 'bar';20 });21 const page = await context.newPage();22 console.log(await page.evaluate(() => window.foo));23 await browser.close();24})();25const { chromium } = require('playwright');26const { pushInitScript } = require('playwright/lib/server/browserContext');27(async () => {28 const browser = await chromium.launch();29 const context = await browser.newContext();30 await pushInitScript(context, () => {31 window.foo = 'bar';32 });33 const page = await context.newPage();34 console.log(await page.evaluate(() => window.foo));35 await browser.close();36})();37const { chromium } = require('playwright');38const { pushInitScript } = require('playwright/lib/server/browserContext');39(async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();42 await pushInitScript(context, () => {43 window.foo = 'bar';44 });45 const page = await context.newPage();46 await page.goto('https

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2const { pushInitScript } = require('playwright/lib/server/browserContext');3pushInitScript(playwright.chromium, function() {4 window.__test = 'test';5});6const playwright = require('playwright');7const { pushInitScript } = require('playwright/lib/server/browserContext');8pushInitScript(playwright.chromium, function() {9 window.__test = 'test';10});11const playwright = require('playwright');12const { pushInitScript } = require('playwright/lib/server/browserContext');13pushInitScript(playwright.chromium, function() {14 window.__test = 'test';15});16const playwright = require('playwright');17const { pushInitScript } = require('playwright/lib/server/browserContext');18pushInitScript(playwright.chromium, function() {19 window.__test = 'test';20});21const playwright = require('playwright');22const { pushInitScript } = require('playwright/lib/server/browserContext');23pushInitScript(playwright.chromium, function() {24 window.__test = 'test';25});26const playwright = require('playwright');27const { pushInitScript } = require('playwright/lib/server/browserContext');28pushInitScript(playwright.chromium, function() {29 window.__test = 'test';30});31const playwright = require('playwright');32const { pushInitScript } = require('playwright/lib/server/browserContext');33pushInitScript(playwright.chromium, function() {34 window.__test = 'test';35});36const playwright = require('playwright');37const { pushInitScript } = require('playwright/lib/server/browserContext');38pushInitScript(playwright.chromium, function() {39 window.__test = 'test';40});41const playwright = require('playwright');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _electron } = require('playwright');2const electronApp = await _electron.launch();3const context = await electronApp.firstWindow();4await context.pushInitScript({path: 'path/to/file.js', args: ['some', 'args']});5await electronApp.close();6const { _electron } = require('playwright');7const electronApp = await _electron.launch();8const context = await electronApp.firstWindow();9await context.pushInitScript({source: 'console.log("hello")'});10await electronApp.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { pushInitScripts } = require('playwright/lib/server/frames');2const { Frame } = require('playwright/lib/server/frames');3const originalMethod = Frame.prototype._navigatedInDocument;4Frame.prototype._navigatedInDocument = function (url, name, documentId, initial) {5 if (initial) {6 pushInitScripts(documentId, 'window.__playwright__ = true;');7 }8 return originalMethod.apply(this, [url, name, documentId, initial]);9};10const playwright = require('playwright');11(async () => {12 const browser = await playwright.chromium.launch({ headless: false });13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.waitForLoadState();16 const result = await page.evaluate(() => {17 return window.__playwright__;18 });19 console.log(result);20 await browser.close();21})();

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful