Best JavaScript code snippet using playwright-internal
TargetRegistry.js
Source:TargetRegistry.js  
...406  updateColorSchemeOverride() {407    this._linkedBrowser.browsingContext.prefersColorSchemeOverride = this.colorScheme || this._browserContext.colorScheme || 'none';408  }409  setReducedMotion(reducedMotion) {410    this.reducedMotion = fromProtocolReducedMotion(reducedMotion);411    this.updateReducedMotionOverride();412  }413  updateReducedMotionOverride() {414    this._linkedBrowser.browsingContext.prefersReducedMotionOverride = this.reducedMotion || this._browserContext.reducedMotion || 'none';415  }416  setForcedColors(forcedColors) {417    this.forcedColors = fromProtocolForcedColors(forcedColors);418    this.updateForcedColorsOverride();419  }420  updateForcedColorsOverride() {421    this._linkedBrowser.browsingContext.forcedColorsOverride = (this.forcedColors !== 'no-override' ? this.forcedColors : this._browserContext.forcedColors) || 'no-override';422  }423  async setViewportSize(viewportSize) {424    this._viewportSize = viewportSize;425    await this.updateViewportSize();426  }427  close(runBeforeUnload = false) {428    this._gBrowser.removeTab(this._tab, {429      skipPermitUnload: !runBeforeUnload,430    });431  }432  channel() {433    return this._channel;434  }435  id() {436    return this._targetId;437  }438  info() {439    return {440      targetId: this.id(),441      type: 'page',442      browserContextId: this._browserContext.browserContextId,443      openerId: this._openerId,444    };445  }446  _onNavigated(aLocation) {447    this._url = aLocation.spec;448    this._browserContext.grantPermissionsToOrigin(this._url);449  }450  async ensurePermissions() {451    await this._channel.connect('').send('ensurePermissions', {}).catch(e => void e);452  }453  async addScriptToEvaluateOnNewDocument(script) {454    await this._channel.connect('').send('addScriptToEvaluateOnNewDocument', script).catch(e => void e);455  }456  async addBinding(worldName, name, script) {457    await this._channel.connect('').send('addBinding', { worldName, name, script }).catch(e => void e);458  }459  async applyContextSetting(name, value) {460    await this._channel.connect('').send('applyContextSetting', { name, value }).catch(e => void e);461  }462  async hasFailedToOverrideTimezone() {463    return await this._channel.connect('').send('hasFailedToOverrideTimezone').catch(e => true);464  }465  async _startVideoRecording({width, height, dir}) {466    // On Mac the window may not yet be visible when TargetCreated and its467    // NSWindow.windowNumber may be -1, so we wait until the window is known468    // to be initialized and visible.469    await this.windowReady();470    const file = OS.Path.join(dir, helper.generateId() + '.webm');471    if (width < 10 || width > 10000 || height < 10 || height > 10000)472      throw new Error("Invalid size");473    const docShell = this._gBrowser.ownerGlobal.docShell;474    // Exclude address bar and navigation control from the video.475    const rect = this.linkedBrowser().getBoundingClientRect();476    const devicePixelRatio = this._window.devicePixelRatio;477    let sessionId;478    const registry = this._registry;479    const screencastClient = {480      QueryInterface: ChromeUtils.generateQI([Ci.nsIScreencastServiceClient]),481      screencastFrame(data, deviceWidth, deviceHeight) {482      },483      screencastStopped() {484        registry.emit(TargetRegistry.Events.ScreencastStopped, sessionId);485      },486    };487    const viewport = this._viewportSize || this._browserContext.defaultViewportSize || { width: 0, height: 0 };488    sessionId = screencastService.startVideoRecording(screencastClient, docShell, true, file, width, height, 0, viewport.width, viewport.height, devicePixelRatio * rect.top);489    this._videoRecordingInfo = { sessionId, file };490    this.emit(PageTarget.Events.ScreencastStarted);491  }492  _stopVideoRecording() {493    if (!this._videoRecordingInfo)494      throw new Error('No video recording in progress');495    const videoRecordingInfo = this._videoRecordingInfo;496    this._videoRecordingInfo = undefined;497    screencastService.stopVideoRecording(videoRecordingInfo.sessionId);498  }499  videoRecordingInfo() {500    return this._videoRecordingInfo;501  }502  async startScreencast({ width, height, quality }) {503    // On Mac the window may not yet be visible when TargetCreated and its504    // NSWindow.windowNumber may be -1, so we wait until the window is known505    // to be initialized and visible.506    await this.windowReady();507    if (width < 10 || width > 10000 || height < 10 || height > 10000)508      throw new Error("Invalid size");509    const docShell = this._gBrowser.ownerGlobal.docShell;510    // Exclude address bar and navigation control from the video.511    const rect = this.linkedBrowser().getBoundingClientRect();512    const devicePixelRatio = this._window.devicePixelRatio;513    const self = this;514    const screencastClient = {515      QueryInterface: ChromeUtils.generateQI([Ci.nsIScreencastServiceClient]),516      screencastFrame(data, deviceWidth, deviceHeight) {517        if (self._screencastRecordingInfo)518          self.emit(PageTarget.Events.ScreencastFrame, { data, deviceWidth, deviceHeight });519      },520      screencastStopped() {521      },522    };523    const viewport = this._viewportSize || this._browserContext.defaultViewportSize || { width: 0, height: 0 };524    const screencastId = screencastService.startVideoRecording(screencastClient, docShell, false, '', width, height, quality || 90, viewport.width, viewport.height, devicePixelRatio * rect.top);525    this._screencastRecordingInfo = { screencastId };526    return { screencastId };527  }528  screencastFrameAck({ screencastId }) {529    if (!this._screencastRecordingInfo || this._screencastRecordingInfo.screencastId !== screencastId)530      return;531    screencastService.screencastFrameAck(screencastId);532  }533  stopScreencast() {534    if (!this._screencastRecordingInfo)535      throw new Error('No screencast in progress');536    const { screencastId } = this._screencastRecordingInfo;537    this._screencastRecordingInfo = undefined;538    screencastService.stopVideoRecording(screencastId);539  }540  dispose() {541    this._disposed = true;542    if (this._videoRecordingInfo)543      this._stopVideoRecording();544    if (this._screencastRecordingInfo)545      this.stopScreencast();546    this._browserContext.pages.delete(this);547    this._registry._browserToTarget.delete(this._linkedBrowser);548    this._registry._browserBrowsingContextToTarget.delete(this._linkedBrowser.browsingContext);549    try {550      helper.removeListeners(this._eventListeners);551    } catch (e) {552      // In some cases, removing listeners from this._linkedBrowser fails553      // because it is already half-destroyed.554      if (e)555        dump(e.message + '\n' + e.stack + '\n');556    }557    this._registry.emit(TargetRegistry.Events.TargetDestroyed, this);558  }559}560PageTarget.Events = {561  ScreencastStarted: Symbol('PageTarget.ScreencastStarted'),562  ScreencastFrame: Symbol('PageTarget.ScreencastFrame'),563  Crashed: Symbol('PageTarget.Crashed'),564  DialogOpened: Symbol('PageTarget.DialogOpened'),565  DialogClosed: Symbol('PageTarget.DialogClosed'),566};567function fromProtocolColorScheme(colorScheme) {568  if (colorScheme === 'light' || colorScheme === 'dark')569    return colorScheme;570  if (colorScheme === null || colorScheme === 'no-preference')571    return undefined;572  throw new Error('Unknown color scheme: ' + colorScheme);573}574function fromProtocolReducedMotion(reducedMotion) {575  if (reducedMotion === 'reduce' || reducedMotion === 'no-preference')576    return reducedMotion;577  if (reducedMotion === null)578    return undefined;579  throw new Error('Unknown reduced motion: ' + reducedMotion);580}581function fromProtocolForcedColors(forcedColors) {582  if (forcedColors === 'active' || forcedColors === 'none')583    return forcedColors;584  if (forcedColors === null)585    return undefined;586  throw new Error('Unknown forced colors: ' + forcedColors);587}588class BrowserContext {589  constructor(registry, browserContextId, removeOnDetach) {590    this._registry = registry;591    this.browserContextId = browserContextId;592    // Default context has userContextId === 0, but we pass undefined to many APIs just in case.593    this.userContextId = 0;594    if (browserContextId !== undefined) {595      const identity = ContextualIdentityService.create(IDENTITY_NAME + browserContextId);596      this.userContextId = identity.userContextId;597    }598    this._principals = [];599    // Maps origins to the permission lists.600    this._permissions = new Map();601    this._registry._browserContextIdToBrowserContext.set(this.browserContextId, this);602    this._registry._userContextIdToBrowserContext.set(this.userContextId, this);603    this._proxy = null;604    this.removeOnDetach = removeOnDetach;605    this.extraHTTPHeaders = undefined;606    this.httpCredentials = undefined;607    this.requestInterceptionEnabled = undefined;608    this.ignoreHTTPSErrors = undefined;609    this.downloadOptions = undefined;610    this.defaultViewportSize = undefined;611    this.deviceScaleFactor = undefined;612    this.defaultUserAgent = null;613    this.defaultPlatform = null;614    this.javaScriptDisabled = false;615    this.touchOverride = false;616    this.colorScheme = 'none';617    this.forcedColors = 'no-override';618    this.reducedMotion = 'none';619    this.videoRecordingOptions = undefined;620    this.scriptsToEvaluateOnNewDocument = [];621    this.bindings = [];622    this.settings = {};623    this.pages = new Set();624  }625  setColorScheme(colorScheme) {626    this.colorScheme = fromProtocolColorScheme(colorScheme);627    for (const page of this.pages)628      page.updateColorSchemeOverride();629  }630  setReducedMotion(reducedMotion) {631    this.reducedMotion = fromProtocolReducedMotion(reducedMotion);632    for (const page of this.pages)633      page.updateReducedMotionOverride();634  }635  setForcedColors(forcedColors) {636    this.forcedColors = fromProtocolForcedColors(forcedColors);637    for (const page of this.pages)638      page.updateForcedColorsOverride();639  }640  async destroy() {641    if (this.userContextId !== 0) {642      ContextualIdentityService.remove(this.userContextId);643      for (const page of this.pages)644        page.close();645      if (this.pages.size) {...Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3  const browser = await chromium.launch();4  const context = await browser.newContext({5  });6  const page = await context.newPage();7  await page.screenshot({path: 'reduced-motion.png'});8  await browser.close();9})();10const {chromium} = require('playwright');11(async () => {12  const browser = await chromium.launch();13  const context = await browser.newContext({14  });15  const page = await context.newPage();16  await page.screenshot({path: 'reduced-motion.png'});17  await browser.close();18})();19await browser.close();20await page.close();21await context.close();22await browser.close();23await browser.close();24await browser.close();25await browser.close();26await browser.close();27await browser.close();28await browser.close();29await browser.close();30await browser.close();31await browser.close();32await browser.close();33await browser.close();34await browser.close();35await browser.close();36await browser.close();Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3  const browser = await chromium.launch({4  });5  const page = await browser.newPage();6  const reducedMotion = await page._client.send('Emulation.getReducedMotion');7  console.log(reducedMotion);8  await browser.close();9})();10const {chromium} = require('playwright');11(async () => {12  const browser = await chromium.launch({13  });14  const page = await browser.newPage();15  const reducedMotion = await page._client.send('Emulation.setReducedMotion', {16  });17  console.log(reducedMotion);18  await browser.close();19})();20const {chromium} = require('playwright');21(async () => {22  const browser = await chromium.launch({23  });24  const page = await browser.newPage();25  const reducedMotion = await page._client.send('Emulation.setReducedMotion', {26  });27  console.log(reducedMotion);28  await browser.close();29})();30const {chromium} = require('playwright');31(async () => {32  const browser = await chromium.launch({33  });34  const page = await browser.newPage();35  const reducedMotion = await page._client.send('Emulation.setVirtualTimePolicy', {36  });37  console.log(reducedMotion);38  await browser.close();39})();40const {chromium} = require('playwright');41(async () => {Using AI Code Generation
1const {chromium} = require('playwright');2const {fromProtocolReducedMotion} = require('playwright-core/lib/server/browserContext');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  await fromProtocolReducedMotion(context, true);7  const page = await context.newPage();8  await page.screenshot({ path: 'reduced-motion.png' });9  await browser.close();10})();Using AI Code Generation
1const { webkit } = require("playwright");2(async () => {3  const browser = await webkit.launch();4  const context = await browser.newContext({5  });6  const page = await context.newPage();7  await page._client.send("Emulation.setEmulatedMedia", {8    features: [{ name: "prefers-reduced-motion", value: "reduce" }],9  });10  const value = await page.$eval(".example img", (element) => {11    return window.getComputedStyle(element).getPropertyValue("animation-play-state");12  });13  console.log(value);14  await browser.close();15})();Using AI Code Generation
1const { webkit } = require('playwright');2(async () => {3  const browser = await webkit.launch();4  const context = await browser.newContext({5    webPreferences: {6      webkit: {7      },8    },9  });10  const page = await context.newPage();11  await page.evaluate(() => {12    const { webkit } = require('playwright');13    return webkit.fromProtocolReducedMotion();14  });15  await browser.close();16})();17const { webkit } = require('playwright');18(async () => {19  const browser = await webkit.launch();20  const context = await browser.newContext({21    webPreferences: {22      webkit: {23      },24    },25  });26  const page = await context.newPage();27  await page.evaluate(() => {28    const { webkit } = require('playwright');29    return webkit.fromProtocolColorScheme();30  });31  await browser.close();32})();33const { webkit } = require('playwright');34(async () => {35  const browser = await webkit.launch();36  const context = await browser.newContext({37    webPreferences: {38      webkit: {39      },40    },41  });42  const page = await context.newPage();43  await page.evaluate(() => {44    const { webkit } = require('playwright');45    return webkit.fromProtocolContrast();46  });47  await browser.close();48})();49const { webkit } = require('playwright');50(async () => {51  const browser = await webkit.launch();52  const context = await browser.newContext({53    webPreferences: {54      webkit: {55      },56    },57  });58  const page = await context.newPage();59  await page.evaluate(() => {60    const { webkit } = require('playwright');Using AI Code Generation
1const { InternalAPI } = require('playwright');2const { chromium } = require('playwright-chromium');3(async () => {4    const browser = await chromium.launch();5    const context = await browser.newContext();6    const page = await context.newPage();7    await page.screenshot({ path: `example.png` });8    await browser.close();9})();10const { InternalAPI } = require('playwright');11const { chromium } = require('playwright-chromium');12(async () => {13    const browser = await chromium.launch();14    const context = await browser.newContext();15    const page = await context.newPage();16    await page.screenshot({ path: `example.png` });17    await browser.close();18})();19const { InternalAPI } = require('playwright');20const { chromium } = require('playwright-chromium');21(async () => {22    const browser = await chromium.launch();23    const context = await browser.newContext();24    const page = await context.newPage();25    await page.screenshot({ path: `example.png` });26    await browser.close();27})();28const { InternalAPI } = require('playwright');29const { chromium } = require('playwright-chromium');30(async () => {31    const browser = await chromium.launch();32    const context = await browser.newContext();33    const page = await context.newPage();34    await page.screenshot({ path: `example.png` });35    await browser.close();36})();37const { InternalAPI } = require('playwright');38const { chromium } = require('playwright-chromium');39(async () => {40    const browser = await chromium.launch();41    const context = await browser.newContext();42    const page = await context.newPage();43    await page.screenshot({ path: `example.png` });44    await browser.close();45})();46const {Using AI Code Generation
1const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');2const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');3const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');4const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');5const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');6const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');7const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');8const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');9const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');10const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');11const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');12const { fromProtocolReducedMotion } = require('playwright/lib/server/supplements/protocolReducedMotion');13const { fromProtocolReducedMotion } = require('playwright/lib/server/supUsing AI Code Generation
1const playwright = require('playwright');2(async () => {3  const browser = await playwright.chromium.launch();4  const page = await browser.newPage();5  const context = await browser.newContext({6  });7  const page = await context.newPage();8  await page.emulateMedia({ reducedMotion: 'reduce' });9  await page.screenshot({ path: `example.png` });10  await browser.close();11})();12const playwright = require('playwright');13(async () => {14  const browser = await playwright.chromium.launch();15  const page = await browser.newPage();16  const context = await browser.newContext({17  });18  const page = await context.newPage();19  await page.emulateMedia({ reducedMotion: 'reduce' });20  await page.screenshot({ path: `example.png` });21  await browser.close();22})();23const playwright = require('playwright');Using AI Code Generation
1const { InternalAPI } = require('@playwright/test');2const { fromProtocolReducedMotion } = InternalAPI;3(async () => {4  await fromProtocolReducedMotion(browserContext, true);5  await fromProtocolReducedMotion(browserContext, false);6})();7const { test, expect } = require('@playwright/test');8test('reduced motion test', async ({ page }) => {9  await page.waitForSelector('text=Google');10  expect(await page.locator('text=Google').isVisible()).toBe(true);11});12test('reduced motion test', async ({ page }) => {13  await page.waitForSelector('text=Google');14  expect(await page.locator('text=Google').isVisible()).toBe(true);15});16test('reduced motion test', async ({ page }) => {17  await page.waitForSelector('text=Google');18  expect(await page.locator('text=Google').isVisible()).toBe(true);19});20test('reduced motion test', async ({ page }) => {21  await page.waitForSelector('text=Google');22  expect(await page.locator('text=Google').isVisible()).toBe(true);23});24test('reduced motion test', async ({ page }) => {25  await page.waitForSelector('text=Google');26  expect(await page.locator('text=Google').isVisible()).toBe(true);27});28test('reduced motion test', async ({ page }) => {29  await page.waitForSelector('text=Google');30  expect(await page.locator('text=Google').isVisible()).toBe(true);31});32test('reduced motion test', async ({ page }) => {33  await page.waitForSelector('text=Google');34  expect(await page.locator('text=Google').isVisible()).toBe(true);35});36test('reduced motion test', async ({ page }) => {37  await page.waitForSelector('text=Google');38  expect(await page.locator('text=Google').isVisible()).toBe(true);39});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.
Get 100 minutes of automation test minutes FREE!!
