Best JavaScript code snippet using playwright-internal
page.js
Source:page.js
...114 }115 initializedOrUndefined() {116 return this._initialized ? this : undefined;117 }118 async _doSlowMo() {119 const slowMo = this._browserContext._browser.options.slowMo;120 if (!slowMo) return;121 await new Promise(x => setTimeout(x, slowMo));122 }123 _didClose() {124 this.instrumentation.onPageClose(this);125 this._frameManager.dispose();126 this._frameThrottler.setEnabled(false);127 (0, _utils.assert)(this._closedState !== 'closed', 'Page closed twice');128 this._closedState = 'closed';129 this.emit(Page.Events.Close);130 this._closedPromise.resolve();131 }132 _didCrash() {133 this.instrumentation.onPageClose(this);134 this._frameManager.dispose();135 this._frameThrottler.setEnabled(false);136 this.emit(Page.Events.Crash);137 this._crashedPromise.resolve(new Error('Page crashed'));138 }139 _didDisconnect() {140 this.instrumentation.onPageClose(this);141 this._frameManager.dispose();142 this._frameThrottler.setEnabled(false);143 (0, _utils.assert)(!this._disconnected, 'Page disconnected twice');144 this._disconnected = true;145 this._disconnectedPromise.resolve(new Error('Page closed'));146 }147 async _onFileChooserOpened(handle) {148 let multiple;149 try {150 multiple = await handle.evaluate(element => !!element.multiple);151 } catch (e) {152 // Frame/context may be gone during async processing. Do not throw.153 return;154 }155 if (!this.listenerCount(Page.Events.FileChooser)) {156 handle.dispose();157 return;158 }159 const fileChooser = new _fileChooser.FileChooser(this, handle, multiple);160 this.emit(Page.Events.FileChooser, fileChooser);161 }162 context() {163 return this._browserContext;164 }165 opener() {166 return this._opener;167 }168 mainFrame() {169 return this._frameManager.mainFrame();170 }171 frames() {172 return this._frameManager.frames();173 }174 setDefaultNavigationTimeout(timeout) {175 this._timeoutSettings.setDefaultNavigationTimeout(timeout);176 }177 setDefaultTimeout(timeout) {178 this._timeoutSettings.setDefaultTimeout(timeout);179 }180 async exposeBinding(name, needsHandle, playwrightBinding) {181 if (this._pageBindings.has(name)) throw new Error(`Function "${name}" has been already registered`);182 if (this._browserContext._pageBindings.has(name)) throw new Error(`Function "${name}" has been already registered in the browser context`);183 const binding = new PageBinding(name, playwrightBinding, needsHandle);184 this._pageBindings.set(name, binding);185 await this._delegate.exposeBinding(binding);186 }187 setExtraHTTPHeaders(headers) {188 this._state.extraHTTPHeaders = headers;189 return this._delegate.updateExtraHTTPHeaders();190 }191 async _onBindingCalled(payload, context) {192 if (this._disconnected || this._closedState === 'closed') return;193 await PageBinding.dispatch(this, payload, context);194 }195 _addConsoleMessage(type, args, location, text) {196 const message = new _console.ConsoleMessage(this, type, text, args, location);197 const intercepted = this._frameManager.interceptConsoleMessage(message);198 if (intercepted || !this.listenerCount(Page.Events.Console)) args.forEach(arg => arg.dispose());else this.emit(Page.Events.Console, message);199 }200 async reload(metadata, options) {201 const controller = new _progress.ProgressController(metadata, this);202 return controller.run(progress => this.mainFrame().raceNavigationAction(async () => {203 // Note: waitForNavigation may fail before we get response to reload(),204 // so we should await it immediately.205 const [response] = await Promise.all([this.mainFrame()._waitForNavigation(progress, options), this._delegate.reload()]);206 await this._doSlowMo();207 return response;208 }), this._timeoutSettings.navigationTimeout(options));209 }210 async goBack(metadata, options) {211 const controller = new _progress.ProgressController(metadata, this);212 return controller.run(progress => this.mainFrame().raceNavigationAction(async () => {213 // Note: waitForNavigation may fail before we get response to goBack,214 // so we should catch it immediately.215 let error;216 const waitPromise = this.mainFrame()._waitForNavigation(progress, options).catch(e => {217 error = e;218 return null;219 });220 const result = await this._delegate.goBack();221 if (!result) return null;222 const response = await waitPromise;223 if (error) throw error;224 await this._doSlowMo();225 return response;226 }), this._timeoutSettings.navigationTimeout(options));227 }228 async goForward(metadata, options) {229 const controller = new _progress.ProgressController(metadata, this);230 return controller.run(progress => this.mainFrame().raceNavigationAction(async () => {231 // Note: waitForNavigation may fail before we get response to goForward,232 // so we should catch it immediately.233 let error;234 const waitPromise = this.mainFrame()._waitForNavigation(progress, options).catch(e => {235 error = e;236 return null;237 });238 const result = await this._delegate.goForward();239 if (!result) return null;240 const response = await waitPromise;241 if (error) throw error;242 await this._doSlowMo();243 return response;244 }), this._timeoutSettings.navigationTimeout(options));245 }246 async emulateMedia(options) {247 if (options.media !== undefined) this._state.mediaType = options.media;248 if (options.colorScheme !== undefined) this._state.colorScheme = options.colorScheme;249 if (options.reducedMotion !== undefined) this._state.reducedMotion = options.reducedMotion;250 if (options.forcedColors !== undefined) this._state.forcedColors = options.forcedColors;251 await this._delegate.updateEmulateMedia();252 await this._doSlowMo();253 }254 async setViewportSize(viewportSize) {255 this._state.emulatedSize = {256 viewport: { ...viewportSize257 },258 screen: { ...viewportSize259 }260 };261 await this._delegate.setEmulatedSize(this._state.emulatedSize);262 await this._doSlowMo();263 }264 viewportSize() {265 var _this$_state$emulated;266 return ((_this$_state$emulated = this._state.emulatedSize) === null || _this$_state$emulated === void 0 ? void 0 : _this$_state$emulated.viewport) || null;267 }268 async bringToFront() {269 await this._delegate.bringToFront();270 }271 async _addInitScriptExpression(source) {272 this._evaluateOnNewDocumentSources.push(source);273 await this._delegate.evaluateOnNewDocument(source);274 }275 _needsRequestInterception() {276 return !!this._clientRequestInterceptor || !!this._serverRequestInterceptor || !!this._browserContext._requestInterceptor;...
input.js
Source:input.js
...92 description.location,93 autoRepeat,94 text95 )96 await this._page._doSlowMo()97 }98 _keyDescriptionForString(keyString) {99 let description = usKeyboardLayout.get(keyString)100 ;(0, _utils.assert)(description, `Unknown key: "${keyString}"`)101 const shift = this._pressedModifiers.has('Shift')102 description =103 shift && description.shifted ? description.shifted : description // if any modifiers besides shift are pressed, no text should be sent104 if (105 this._pressedModifiers.size > 1 ||106 (!this._pressedModifiers.has('Shift') &&107 this._pressedModifiers.size === 1)108 )109 return { ...description, text: '' }110 return description111 }112 async up(key) {113 const description = this._keyDescriptionForString(key)114 if (kModifiers.includes(description.key))115 this._pressedModifiers.delete(description.key)116 this._pressedKeys.delete(description.code)117 await this._raw.keyup(118 this._pressedModifiers,119 description.code,120 description.keyCode,121 description.keyCodeWithoutLocation,122 description.key,123 description.location124 )125 await this._page._doSlowMo()126 }127 async insertText(text) {128 await this._raw.sendText(text)129 await this._page._doSlowMo()130 }131 async imeSetComposition(text, selectionStart, selectionEnd, options) {132 let replacementStart = -1133 let replacementEnd = -1134 if (options && options.replacementStart !== undefined)135 replacementStart = options.replacementStart136 if (options && options.replacementEnd !== undefined)137 replacementEnd = options.replacementEnd138 await this._raw.imeSetComposition(139 text,140 selectionStart,141 selectionEnd,142 replacementStart,143 replacementEnd144 )145 await this._page._doSlowMo()146 }147 async type(text, options) {148 const delay = (options && options.delay) || undefined149 for (const char of text) {150 if (usKeyboardLayout.has(char)) {151 await this.press(char, {152 delay153 })154 } else {155 if (delay) await new Promise((f) => setTimeout(f, delay))156 await this.insertText(char)157 }158 }159 }160 async press(key, options = {}) {161 function split(keyString) {162 const keys = []163 let building = ''164 for (const char of keyString) {165 if (char === '+' && building) {166 keys.push(building)167 building = ''168 } else {169 building += char170 }171 }172 keys.push(building)173 return keys174 }175 const tokens = split(key)176 const promises = []177 key = tokens[tokens.length - 1]178 for (let i = 0; i < tokens.length - 1; ++i)179 promises.push(this.down(tokens[i]))180 promises.push(this.down(key))181 if (options.delay) {182 await Promise.all(promises)183 await new Promise((f) => setTimeout(f, options.delay))184 }185 promises.push(this.up(key))186 for (let i = tokens.length - 2; i >= 0; --i)187 promises.push(this.up(tokens[i]))188 await Promise.all(promises)189 }190 async _ensureModifiers(modifiers) {191 for (const modifier of modifiers) {192 if (!kModifiers.includes(modifier))193 throw new Error('Unknown modifier ' + modifier)194 }195 const restore = Array.from(this._pressedModifiers)196 const promises = []197 for (const key of kModifiers) {198 const needDown = modifiers.includes(key)199 const isDown = this._pressedModifiers.has(key)200 if (needDown && !isDown) promises.push(this.down(key))201 else if (!needDown && isDown) promises.push(this.up(key))202 }203 await Promise.all(promises)204 return restore205 }206 _modifiers() {207 return this._pressedModifiers208 }209}210exports.Keyboard = Keyboard211class Mouse {212 constructor(raw, page) {213 this._keyboard = void 0214 this._x = 0215 this._y = 0216 this._lastButton = 'none'217 this._buttons = new Set()218 this._raw = void 0219 this._page = void 0220 this._raw = raw221 this._page = page222 this._keyboard = this._page.keyboard223 }224 async move(x, y, options = {}) {225 const { steps = 1 } = options226 const fromX = this._x227 const fromY = this._y228 this._x = x229 this._y = y230 for (let i = 1; i <= steps; i++) {231 const middleX = fromX + (x - fromX) * (i / steps)232 const middleY = fromY + (y - fromY) * (i / steps)233 await this._raw.move(234 middleX,235 middleY,236 this._lastButton,237 this._buttons,238 this._keyboard._modifiers()239 )240 await this._page._doSlowMo()241 }242 }243 async down(options = {}) {244 const { button = 'left', clickCount = 1 } = options245 this._lastButton = button246 this._buttons.add(button)247 await this._raw.down(248 this._x,249 this._y,250 this._lastButton,251 this._buttons,252 this._keyboard._modifiers(),253 clickCount254 )255 await this._page._doSlowMo()256 }257 async up(options = {}) {258 const { button = 'left', clickCount = 1 } = options259 this._lastButton = 'none'260 this._buttons.delete(button)261 await this._raw.up(262 this._x,263 this._y,264 button,265 this._buttons,266 this._keyboard._modifiers(),267 clickCount268 )269 await this._page._doSlowMo()270 }271 async click(x, y, options = {}) {272 const { delay = null, clickCount = 1 } = options273 if (delay) {274 this.move(x, y)275 for (let cc = 1; cc <= clickCount; ++cc) {276 await this.down({ ...options, clickCount: cc })277 await new Promise((f) => setTimeout(f, delay))278 await this.up({ ...options, clickCount: cc })279 if (cc < clickCount) await new Promise((f) => setTimeout(f, delay))280 }281 } else {282 const promises = []283 promises.push(this.move(x, y))284 for (let cc = 1; cc <= clickCount; ++cc) {285 promises.push(this.down({ ...options, clickCount: cc }))286 promises.push(this.up({ ...options, clickCount: cc }))287 }288 await Promise.all(promises)289 }290 }291 async dblclick(x, y, options = {}) {292 await this.click(x, y, { ...options, clickCount: 2 })293 }294 async wheel(deltaX, deltaY) {295 await this._raw.wheel(296 this._x,297 this._y,298 this._buttons,299 this._keyboard._modifiers(),300 deltaX,301 deltaY302 )303 await this._page._doSlowMo()304 }305}306exports.Mouse = Mouse307const aliases = new Map([308 ['ShiftLeft', ['Shift']],309 ['ControlLeft', ['Control']],310 ['AltLeft', ['Alt']],311 ['MetaLeft', ['Meta']],312 ['Enter', ['\n', '\r']]313])314const usKeyboardLayout = buildLayoutClosure(keyboardLayout.USKeyboardLayout)315function buildLayoutClosure(layout) {316 const result = new Map()317 for (const code in layout) {318 const definition = layout[code]319 const description = {320 key: definition.key || '',321 keyCode: definition.keyCode || 0,322 keyCodeWithoutLocation:323 definition.keyCodeWithoutLocation || definition.keyCode || 0,324 code,325 text: definition.text || '',326 location: definition.location || 0327 }328 if (definition.key.length === 1) description.text = description.key // Generate shifted definition.329 let shiftedDescription330 if (definition.shiftKey) {331 ;(0, _utils.assert)(definition.shiftKey.length === 1)332 shiftedDescription = { ...description }333 shiftedDescription.key = definition.shiftKey334 shiftedDescription.text = definition.shiftKey335 if (definition.shiftKeyCode)336 shiftedDescription.keyCode = definition.shiftKeyCode337 } // Map from code: Digit3 -> { ... descrption, shifted }338 result.set(code, { ...description, shifted: shiftedDescription }) // Map from aliases: Shift -> non-shiftable definition339 if (aliases.has(code)) {340 for (const alias of aliases.get(code)) result.set(alias, description)341 } // Do not use numpad when converting keys to codes.342 if (definition.location) continue // Map from key, no shifted343 if (description.key.length === 1) result.set(description.key, description) // Map from shiftKey, no shifted344 if (shiftedDescription)345 result.set(shiftedDescription.key, {346 ...shiftedDescription,347 shifted: undefined348 })349 }350 return result351}352class Touchscreen {353 constructor(raw, page) {354 this._raw = void 0355 this._page = void 0356 this._raw = raw357 this._page = page358 }359 async tap(x, y) {360 if (!this._page._browserContext._options.hasTouch)361 throw new Error(362 'hasTouch must be enabled on the browser context before using the touchscreen.'363 )364 await this._raw.tap(x, y, this._page.keyboard._modifiers())365 await this._page._doSlowMo()366 }367}...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page._doSlowMo();6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const page = await browser.newPage();12 await page._doSlowMo(1000);13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch();18 const page = await browser.newPage();19 await page._doSlowMo(1000);20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const page = await browser.newPage();26 await page._doSlowMo(1000);27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const page = await browser.newPage();33 await page._doSlowMo(1000);34 await browser.close();35})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const page = await browser.newPage();5 await page._doSlowMo();6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch({ headless: false });11 const page = await browser.newPage();12 await page._doSlowMo();13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch({ headless: false });18 const page = await browser.newPage();19 await page._doSlowMo();20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch({ headless: false });25 const page = await browser.newPage();26 await page._doSlowMo();27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch({ headless: false });32 const page = await browser.newPage();33 await page._doSlowMo();34 await browser.close();35})();36const { chromium } = require('playwright');37(async () => {38 const browser = await chromium.launch({ headless: false });39 const page = await browser.newPage();40 await page._doSlowMo();41 await browser.close();42})();
Using AI Code Generation
1const playwright = require("playwright");2const { _doSlowMo } = require("playwright/lib/server/slowMo");3(async () => {4 const browser = await playwright.chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await _doSlowMo(1000);8 await page.screenshot({ path: "example.png" });9 await browser.close();10})();
Using AI Code Generation
1const playwright = require('playwright');2const { _doSlowMo } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');3(async () => {4 const browser = await playwright.chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.fill('input[name="q"]', 'Hello World');8 await page.click('input[type="submit"]');9 await _doSlowMo(page);10 await page.screenshot({ path: 'example.png' });11 await browser.close();12})();13const { helper } = require('../../helper');14const { assert } = require('../../assert');15const { SlowMoRecorder } = require('./slowMoRecorder');16const { SlowMoRecorderController } = require('./slowMoRecorderController');17const { SlowMoRecorderModel } = require('./slowMoRecorderModel');18const { SlowMoRecorderView } = require('./slowMoRecorderView');19class SlowMoRecorderSupplement {20 constructor(context) {21 this._context = context;22 this._slowMoRecorder = new SlowMoRecorder(context);23 }24 async _doSlowMo(page) {25 const controller = new SlowMoRecorderController(this._slowMoRecorder, page);26 const model = new SlowMoRecorderModel();27 const view = new SlowMoRecorderView();28 await controller.start();29 await model.start();30 await view.start();31 await controller.stop();32 await model.stop();33 await view.stop();34 }35}36helper.tracePublicAPI(SlowMoRecorderSupplement);37module.exports = { SlowMoRecorderSupplement };38const { helper } = require('../../helper');39const { assert } = require('../../assert');40const { SlowMoRecorderController } = require('./slowMoRecorderController');41const { SlowMoRecorderModel } = require('./slowMoRecorderModel');42const { SlowMoRecorderView } = require('./slowMoRecorderView');43class SlowMoRecorder {44 constructor(context) {45 this._context = context;46 this._slowMoRecorder = new SlowMoRecorder(context);
Using AI Code Generation
1const { _doSlowMo } = require('playwright/lib/server/slowMo');2const { _doSlowMo } = require('playwright/lib/server/slowMo');3const { _doSlowMo } = require('playwright/lib/server/slowMo');4const { _doSlowMo } = require('playwright/lib/server/slowMo');5const { _doSlowMo } = require('playwright/lib/server/slowMo');6const { _doSlowMo } = require('playwright/lib/server/slowMo');7const { _doSlowMo } = require('playwright/lib/server/slowMo');8const { _doSlowMo } = require('playwright/lib/server/slowMo');9const { _doSlowMo } = require('playwright/lib/server/slowMo');10const { _doSlowMo } = require('playwright/lib/server/slowMo');11const { _doSlowMo } = require('playwright/lib/server/slowMo');12const { _doSlowMo } = require('playwright/lib/server/slowMo');13const { _doSlowMo } = require('playwright/lib/server/slowMo');14const { _doSlowMo } = require('playwright/lib/server/slowMo');15const { _doSlowMo } = require('playwright/lib/server/slowMo');16const {
Using AI Code Generation
1const { _doSlowMo } = require('@playwright/test/lib/server/trace/recorder/slowmo');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await _doSlowMo(page);7 await browser.close();8})();9const { BrowserContext } = require('../browserContext');10const { Page } = require('../page');11async function _doSlowMo(page) {12 const delay = 1000;13 const context = page.context();14 await context.tracing.start({ screenshots: true, snapshots: true });15 await page.screenshot({ path: `before.png` });16 await page.waitForTimeout(delay);17 await page.screenshot({ path: `after.png` });18 await context.tracing.stop({ path: `trace.zip` });19}20module.exports = { _doSlowMo };
Using AI Code Generation
1const { InternalAPIs } = require('playwright');2InternalAPIs._doSlowMo = (delay) => {3 return new Promise((resolve) => setTimeout(resolve, delay));4};5module.exports = {6 launchOptions: {7 },8};
Using AI Code Generation
1const { _doSlowMo } = require('playwright/lib/server/slowMo');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('text=Images');8 await _doSlowMo(2000);9 await page.click('text=News');10 await _doSlowMo(2000);11 await page.click('text=Videos');12 await _doSlowMo(2000);13 await page.click('text=Maps');14 await _doSlowMo(2000);15 await page.click('text=Explore');16 await _doSlowMo(2000);17 await page.click('text=Shopping');18 await _doSlowMo(2000);19 await page.click('text=Sign in');20 await page.click('input[name="loginfmt"]');21 await page.fill('input[name="loginfmt"]', 'testuser');22 await page.click('input[type="submit"]');23 await page.click('input[name="passwd"]');24 await page.fill('input[name="passwd"]', 'testpassword');25 await page.click('input[type="submit"]');26 await page.click('text=Sign in');27 await page.click('text=Search');28 await browser.close();29})();30const { _doSlowMo } = require('playwright/lib/server/slowMo');31const { chromium } = require('playwright');32(async () => {33 const browser = await chromium.launch({ headless: false });34 const context = await browser.newContext();35 const page = await context.newPage();36 await page.click('text=Images');37 await _doSlowMo(2000);38 await page.click('text=News');39 await _doSlowMo(2000);40 await page.click('text=Videos');41 await _doSlowMo(2000);42 await page.click('text=Maps');
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!!