Best JavaScript code snippet using playwright-internal
browserContext.js
Source: browserContext.js
...337 RequestFinished: 'requestfinished',338 BeforeClose: 'beforeclose',339 VideoStarted: 'videostarted'340};341function assertBrowserContextIsNotOwned(context) {342 for (const page of context.pages()) {343 if (page._ownedContext) throw new Error('Please use browser.newContext() for multi-page scripts that share the context.');344 }345}346function validateBrowserContextOptions(options, browserOptions) {347 if (options.noDefaultViewport && options.deviceScaleFactor !== undefined) throw new Error(`"deviceScaleFactor" option is not supported with null "viewport"`);348 if (options.noDefaultViewport && options.isMobile !== undefined) throw new Error(`"isMobile" option is not supported with null "viewport"`);349 if (options.acceptDownloads === undefined) options.acceptDownloads = true;350 if (!options.viewport && !options.noDefaultViewport) options.viewport = {351 width: 1280,352 height: 720353 };354 if (options.recordVideo) {355 if (!options.recordVideo.size) {...
ffBrowser.js
Source: ffBrowser.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.FFBrowserContext = exports.FFBrowser = void 0;6var _errors = require("../../utils/errors");7var _utils = require("../../utils/utils");8var _browser = require("../browser");9var _browserContext = require("../browserContext");10var network = _interopRequireWildcard(require("../network"));11var _ffConnection = require("./ffConnection");12var _ffPage = require("./ffPage");13function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }14function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }15/**16 * Copyright 2018 Google Inc. All rights reserved.17 * Modifications copyright (c) Microsoft Corporation.18 *19 * Licensed under the Apache License, Version 2.0 (the 'License');20 * you may not use this file except in compliance with the License.21 * You may obtain a copy of the License at22 *23 * http://www.apache.org/licenses/LICENSE-2.024 *25 * Unless required by applicable law or agreed to in writing, software26 * distributed under the License is distributed on an 'AS IS' BASIS,27 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.28 * See the License for the specific language governing permissions and29 * limitations under the License.30 */31class FFBrowser extends _browser.Browser {32 static async connect(transport, options) {33 const connection = new _ffConnection.FFConnection(transport, options.protocolLogger, options.browserLogsCollector);34 const browser = new FFBrowser(connection, options);35 if (options.__testHookOnConnectToBrowser) await options.__testHookOnConnectToBrowser();36 const promises = [connection.send('Browser.enable', {37 attachToDefaultContext: !!options.persistent38 }), browser._initVersion()];39 if (options.persistent) {40 browser._defaultContext = new FFBrowserContext(browser, undefined, options.persistent);41 promises.push(browser._defaultContext._initialize());42 }43 if (options.proxy) promises.push(browser._connection.send('Browser.setBrowserProxy', toJugglerProxyOptions(options.proxy)));44 await Promise.all(promises);45 return browser;46 }47 constructor(connection, options) {48 super(options);49 this._connection = void 0;50 this._ffPages = void 0;51 this._contexts = void 0;52 this._version = '';53 this._userAgent = '';54 this._connection = connection;55 this._ffPages = new Map();56 this._contexts = new Map();57 this._connection.on(_ffConnection.ConnectionEvents.Disconnected, () => this._onDisconnect());58 this._connection.on('Browser.attachedToTarget', this._onAttachedToTarget.bind(this));59 this._connection.on('Browser.detachedFromTarget', this._onDetachedFromTarget.bind(this));60 this._connection.on('Browser.downloadCreated', this._onDownloadCreated.bind(this));61 this._connection.on('Browser.downloadFinished', this._onDownloadFinished.bind(this));62 this._connection.on('Browser.videoRecordingFinished', this._onVideoRecordingFinished.bind(this));63 }64 async _initVersion() {65 const result = await this._connection.send('Browser.getInfo');66 this._version = result.version.substring(result.version.indexOf('/') + 1);67 this._userAgent = result.userAgent;68 }69 isConnected() {70 return !this._connection._closed;71 }72 async newContext(options) {73 (0, _browserContext.validateBrowserContextOptions)(options, this.options);74 if (options.isMobile) throw new Error('options.isMobile is not supported in Firefox');75 const {76 browserContextId77 } = await this._connection.send('Browser.createBrowserContext', {78 removeOnDetach: true79 });80 const context = new FFBrowserContext(this, browserContextId, options);81 await context._initialize();82 this._contexts.set(browserContextId, context);83 return context;84 }85 contexts() {86 return Array.from(this._contexts.values());87 }88 version() {89 return this._version;90 }91 userAgent() {92 return this._userAgent;93 }94 _onDetachedFromTarget(payload) {95 const ffPage = this._ffPages.get(payload.targetId);96 this._ffPages.delete(payload.targetId);97 ffPage.didClose();98 }99 _onAttachedToTarget(payload) {100 const {101 targetId,102 browserContextId,103 openerId,104 type105 } = payload.targetInfo;106 (0, _utils.assert)(type === 'page');107 const context = browserContextId ? this._contexts.get(browserContextId) : this._defaultContext;108 (0, _utils.assert)(context, `Unknown context id:${browserContextId}, _defaultContext: ${this._defaultContext}`);109 const session = this._connection.createSession(payload.sessionId);110 const opener = openerId ? this._ffPages.get(openerId) : null;111 const ffPage = new _ffPage.FFPage(session, context, opener);112 this._ffPages.set(targetId, ffPage);113 }114 _onDownloadCreated(payload) {115 const ffPage = this._ffPages.get(payload.pageTargetId);116 (0, _utils.assert)(ffPage);117 if (!ffPage) return;118 let originPage = ffPage._initializedPage; // If it's a new window download, report it on the opener page.119 if (!originPage) {120 // Resume the page creation with an error. The page will automatically close right121 // after the download begins.122 ffPage._markAsError(new Error('Starting new page download'));123 if (ffPage._opener) originPage = ffPage._opener._initializedPage;124 }125 if (!originPage) return;126 this._downloadCreated(originPage, payload.uuid, payload.url, payload.suggestedFileName);127 }128 _onDownloadFinished(payload) {129 const error = payload.canceled ? 'canceled' : payload.error;130 this._downloadFinished(payload.uuid, error);131 }132 _onVideoRecordingFinished(payload) {133 var _this$_takeVideo;134 (_this$_takeVideo = this._takeVideo(payload.screencastId)) === null || _this$_takeVideo === void 0 ? void 0 : _this$_takeVideo.reportFinished();135 }136 _onDisconnect() {137 for (const video of this._idToVideo.values()) video.artifact.reportFinished(_errors.kBrowserClosedError);138 this._idToVideo.clear();139 this._didClose();140 }141}142exports.FFBrowser = FFBrowser;143class FFBrowserContext extends _browserContext.BrowserContext {144 constructor(browser, browserContextId, options) {145 super(browser, options, browserContextId);146 }147 async _initialize() {148 (0, _utils.assert)(!this._ffPages().length);149 const browserContextId = this._browserContextId;150 const promises = [super._initialize()];151 promises.push(this._browser._connection.send('Browser.setDownloadOptions', {152 browserContextId,153 downloadOptions: {154 behavior: this._options.acceptDownloads ? 'saveToDisk' : 'cancel',155 downloadsDir: this._browser.options.downloadsPath156 }157 }));158 if (this._options.viewport) {159 const viewport = {160 viewportSize: {161 width: this._options.viewport.width,162 height: this._options.viewport.height163 },164 deviceScaleFactor: this._options.deviceScaleFactor || 1165 };166 promises.push(this._browser._connection.send('Browser.setDefaultViewport', {167 browserContextId,168 viewport169 }));170 }171 if (this._options.hasTouch) promises.push(this._browser._connection.send('Browser.setTouchOverride', {172 browserContextId,173 hasTouch: true174 }));175 if (this._options.userAgent) promises.push(this._browser._connection.send('Browser.setUserAgentOverride', {176 browserContextId,177 userAgent: this._options.userAgent178 }));179 if (this._options.bypassCSP) promises.push(this._browser._connection.send('Browser.setBypassCSP', {180 browserContextId,181 bypassCSP: true182 }));183 if (this._options.ignoreHTTPSErrors) promises.push(this._browser._connection.send('Browser.setIgnoreHTTPSErrors', {184 browserContextId,185 ignoreHTTPSErrors: true186 }));187 if (this._options.javaScriptEnabled === false) promises.push(this._browser._connection.send('Browser.setJavaScriptDisabled', {188 browserContextId,189 javaScriptDisabled: true190 }));191 if (this._options.locale) promises.push(this._browser._connection.send('Browser.setLocaleOverride', {192 browserContextId,193 locale: this._options.locale194 }));195 if (this._options.timezoneId) promises.push(this._browser._connection.send('Browser.setTimezoneOverride', {196 browserContextId,197 timezoneId: this._options.timezoneId198 }));199 if (this._options.permissions) promises.push(this.grantPermissions(this._options.permissions));200 if (this._options.extraHTTPHeaders || this._options.locale) promises.push(this.setExtraHTTPHeaders(this._options.extraHTTPHeaders || []));201 if (this._options.httpCredentials) promises.push(this.setHTTPCredentials(this._options.httpCredentials));202 if (this._options.geolocation) promises.push(this.setGeolocation(this._options.geolocation));203 if (this._options.offline) promises.push(this.setOffline(this._options.offline));204 promises.push(this._browser._connection.send('Browser.setColorScheme', {205 browserContextId,206 colorScheme: this._options.colorScheme !== undefined ? this._options.colorScheme : 'light'207 }));208 // [Replay] - Browser.setReducedMotion and Browser.setReducedMotion are not supported209 // promises.push(this._browser._connection.send('Browser.setReducedMotion', {210 // browserContextId,211 // reducedMotion: this._options.reducedMotion !== undefined ? this._options.reducedMotion : 'no-preference'212 // }));213 // promises.push(this._browser._connection.send('Browser.setReducedMotion', {214 // browserContextId,215 // forcedColors: this._options.forcedColors !== undefined ? this._options.forcedColors : 'none'216 // }));217 if (this._options.recordVideo) {218 promises.push(this._ensureVideosPath().then(() => {219 return this._browser._connection.send('Browser.setVideoRecordingOptions', {220 // validateBrowserContextOptions ensures correct video size.221 options: { ...this._options.recordVideo.size,222 dir: this._options.recordVideo.dir223 },224 browserContextId: this._browserContextId225 });226 }));227 }228 if (this._options.proxy) {229 promises.push(this._browser._connection.send('Browser.setContextProxy', {230 browserContextId: this._browserContextId,231 ...toJugglerProxyOptions(this._options.proxy)232 }));233 }234 await Promise.all(promises);235 }236 _ffPages() {237 return Array.from(this._browser._ffPages.values()).filter(ffPage => ffPage._browserContext === this);238 }239 pages() {240 return this._ffPages().map(ffPage => ffPage._initializedPage).filter(pageOrNull => !!pageOrNull);241 }242 async newPageDelegate() {243 (0, _browserContext.assertBrowserContextIsNotOwned)(this);244 const {245 targetId246 } = await this._browser._connection.send('Browser.newPage', {247 browserContextId: this._browserContextId248 }).catch(e => {249 if (e.message.includes('Failed to override timezone')) throw new Error(`Invalid timezone ID: ${this._options.timezoneId}`);250 throw e;251 });252 return this._browser._ffPages.get(targetId);253 }254 async _doCookies(urls) {255 const {256 cookies257 } = await this._browser._connection.send('Browser.getCookies', {258 browserContextId: this._browserContextId259 });260 return network.filterCookies(cookies.map(c => {261 const copy = { ...c262 };263 delete copy.size;264 delete copy.session;265 return copy;266 }), urls);267 }268 async addCookies(cookies) {269 const cc = network.rewriteCookies(cookies).map(c => ({ ...c,270 expires: c.expires && c.expires !== -1 ? c.expires : undefined271 }));272 await this._browser._connection.send('Browser.setCookies', {273 browserContextId: this._browserContextId,274 cookies: cc275 });276 }277 async clearCookies() {278 await this._browser._connection.send('Browser.clearCookies', {279 browserContextId: this._browserContextId280 });281 }282 async _doGrantPermissions(origin, permissions) {283 const webPermissionToProtocol = new Map([['geolocation', 'geo'], ['persistent-storage', 'persistent-storage'], ['push', 'push'], ['notifications', 'desktop-notification']]);284 const filtered = permissions.map(permission => {285 const protocolPermission = webPermissionToProtocol.get(permission);286 if (!protocolPermission) throw new Error('Unknown permission: ' + permission);287 return protocolPermission;288 });289 await this._browser._connection.send('Browser.grantPermissions', {290 origin: origin,291 browserContextId: this._browserContextId,292 permissions: filtered293 });294 }295 async _doClearPermissions() {296 await this._browser._connection.send('Browser.resetPermissions', {297 browserContextId: this._browserContextId298 });299 }300 async setGeolocation(geolocation) {301 (0, _browserContext.verifyGeolocation)(geolocation);302 this._options.geolocation = geolocation;303 await this._browser._connection.send('Browser.setGeolocationOverride', {304 browserContextId: this._browserContextId,305 geolocation: geolocation || null306 });307 }308 async setExtraHTTPHeaders(headers) {309 this._options.extraHTTPHeaders = headers;310 let allHeaders = this._options.extraHTTPHeaders;311 if (this._options.locale) allHeaders = network.mergeHeaders([allHeaders, network.singleHeader('Accept-Language', this._options.locale)]);312 await this._browser._connection.send('Browser.setExtraHTTPHeaders', {313 browserContextId: this._browserContextId,314 headers: allHeaders315 });316 }317 async setOffline(offline) {318 this._options.offline = offline;319 await this._browser._connection.send('Browser.setOnlineOverride', {320 browserContextId: this._browserContextId,321 override: offline ? 'offline' : 'online'322 });323 }324 async _doSetHTTPCredentials(httpCredentials) {325 this._options.httpCredentials = httpCredentials;326 await this._browser._connection.send('Browser.setHTTPCredentials', {327 browserContextId: this._browserContextId,328 credentials: httpCredentials || null329 });330 }331 async _doAddInitScript(source) {332 await this._browser._connection.send('Browser.addScriptToEvaluateOnNewDocument', {333 browserContextId: this._browserContextId,334 script: source335 });336 }337 async _doExposeBinding(binding) {338 await this._browser._connection.send('Browser.addBinding', {339 browserContextId: this._browserContextId,340 name: binding.name,341 script: binding.source342 });343 }344 async _doUpdateRequestInterception() {345 await this._browser._connection.send('Browser.setRequestInterception', {346 browserContextId: this._browserContextId,347 enabled: !!this._requestInterceptor348 });349 }350 _onClosePersistent() {}351 async _doClose() {352 (0, _utils.assert)(this._browserContextId);353 await this._browser._connection.send('Browser.removeBrowserContext', {354 browserContextId: this._browserContextId355 });356 this._browser._contexts.delete(this._browserContextId);357 }358 async _doCancelDownload(uuid) {359 await this._browser._connection.send('Browser.cancelDownload', {360 uuid361 });362 }363}364exports.FFBrowserContext = FFBrowserContext;365function toJugglerProxyOptions(proxy) {366 const proxyServer = new URL(proxy.server);367 let port = parseInt(proxyServer.port, 10);368 let type = 'http';369 if (proxyServer.protocol === 'socks5:') type = 'socks';else if (proxyServer.protocol === 'socks4:') type = 'socks4';else if (proxyServer.protocol === 'https:') type = 'https';370 if (proxyServer.port === '') {371 if (proxyServer.protocol === 'http:') port = 80;else if (proxyServer.protocol === 'https:') port = 443;372 }373 return {374 type,375 bypass: proxy.bypass ? proxy.bypass.split(',').map(domain => domain.trim()) : [],376 host: proxyServer.hostname,377 port,378 username: proxy.username,379 password: proxy.password380 };...
wkBrowser.js
Source: wkBrowser.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.WKBrowserContext = exports.WKBrowser = void 0;6var _browser = require("../browser");7var _browserContext = require("../browserContext");8var _eventsHelper = require("../../utils/eventsHelper");9var _utils = require("../../utils/utils");10var network = _interopRequireWildcard(require("../network"));11var _wkConnection = require("./wkConnection");12var _wkPage = require("./wkPage");13var _errors = require("../../utils/errors");14function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }15function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }16/**17 * Copyright 2017 Google Inc. All rights reserved.18 * Modifications copyright (c) Microsoft Corporation.19 *20 * Licensed under the Apache License, Version 2.0 (the "License");21 * you may not use this file except in compliance with the License.22 * You may obtain a copy of the License at23 *24 * http://www.apache.org/licenses/LICENSE-2.025 *26 * Unless required by applicable law or agreed to in writing, software27 * distributed under the License is distributed on an "AS IS" BASIS,28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.29 * See the License for the specific language governing permissions and30 * limitations under the License.31 */32const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15';33const BROWSER_VERSION = '15.4';34class WKBrowser extends _browser.Browser {35 static async connect(transport, options) {36 const browser = new WKBrowser(transport, options);37 if (options.__testHookOnConnectToBrowser) await options.__testHookOnConnectToBrowser();38 const promises = [browser._browserSession.send('Playwright.enable')];39 if (options.persistent) {40 browser._defaultContext = new WKBrowserContext(browser, undefined, options.persistent);41 promises.push(browser._defaultContext._initialize());42 }43 await Promise.all(promises);44 return browser;45 }46 constructor(transport, options) {47 super(options);48 this._connection = void 0;49 this._browserSession = void 0;50 this._contexts = new Map();51 this._wkPages = new Map();52 this._eventListeners = void 0;53 this._connection = new _wkConnection.WKConnection(transport, this._onDisconnect.bind(this), options.protocolLogger, options.browserLogsCollector);54 this._browserSession = this._connection.browserSession;55 this._eventListeners = [_eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.pageProxyCreated', this._onPageProxyCreated.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.pageProxyDestroyed', this._onPageProxyDestroyed.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.provisionalLoadFailed', event => this._onProvisionalLoadFailed(event)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.windowOpen', event => this._onWindowOpen(event)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.downloadCreated', this._onDownloadCreated.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.downloadFilenameSuggested', this._onDownloadFilenameSuggested.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.downloadFinished', this._onDownloadFinished.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.screencastFinished', this._onScreencastFinished.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, _wkConnection.kPageProxyMessageReceived, this._onPageProxyMessageReceived.bind(this))];56 }57 _onDisconnect() {58 for (const wkPage of this._wkPages.values()) wkPage.dispose(true);59 for (const video of this._idToVideo.values()) video.artifact.reportFinished(_errors.kBrowserClosedError);60 this._idToVideo.clear();61 this._didClose();62 }63 async newContext(options) {64 (0, _browserContext.validateBrowserContextOptions)(options, this.options);65 const createOptions = options.proxy ? {66 proxyServer: options.proxy.server,67 proxyBypassList: options.proxy.bypass68 } : undefined;69 const {70 browserContextId71 } = await this._browserSession.send('Playwright.createContext', createOptions);72 options.userAgent = options.userAgent || DEFAULT_USER_AGENT;73 const context = new WKBrowserContext(this, browserContextId, options);74 await context._initialize();75 this._contexts.set(browserContextId, context);76 return context;77 }78 contexts() {79 return Array.from(this._contexts.values());80 }81 version() {82 return BROWSER_VERSION;83 }84 userAgent() {85 return DEFAULT_USER_AGENT;86 }87 _onDownloadCreated(payload) {88 const page = this._wkPages.get(payload.pageProxyId);89 if (!page) return; // In some cases, e.g. blob url download, we receive only frameScheduledNavigation90 // but no signals that the navigation was canceled and replaced by download. Fix it91 // here by simulating cancelled provisional load which matches downloads from network.92 //93 // TODO: this is racy, because download might be unrelated any navigation, and we will94 // abort navgitation that is still running. We should be able to fix this by95 // instrumenting policy decision start/proceed/cancel.96 page._page._frameManager.frameAbortedNavigation(payload.frameId, 'Download is starting');97 let originPage = page._initializedPage; // If it's a new window download, report it on the opener page.98 if (!originPage) {99 // Resume the page creation with an error. The page will automatically close right100 // after the download begins.101 page._firstNonInitialNavigationCommittedReject(new Error('Starting new page download'));102 if (page._opener) originPage = page._opener._initializedPage;103 }104 if (!originPage) return;105 this._downloadCreated(originPage, payload.uuid, payload.url);106 }107 _onDownloadFilenameSuggested(payload) {108 this._downloadFilenameSuggested(payload.uuid, payload.suggestedFilename);109 }110 _onDownloadFinished(payload) {111 this._downloadFinished(payload.uuid, payload.error);112 }113 _onScreencastFinished(payload) {114 var _this$_takeVideo;115 (_this$_takeVideo = this._takeVideo(payload.screencastId)) === null || _this$_takeVideo === void 0 ? void 0 : _this$_takeVideo.reportFinished();116 }117 _onPageProxyCreated(event) {118 const pageProxyId = event.pageProxyId;119 let context = null;120 if (event.browserContextId) {121 // FIXME: we don't know about the default context id, so assume that all targets from122 // unknown contexts are created in the 'default' context which can in practice be represented123 // by multiple actual contexts in WebKit. Solving this properly will require adding context124 // lifecycle events.125 context = this._contexts.get(event.browserContextId) || null;126 }127 if (!context) context = this._defaultContext;128 if (!context) return;129 const pageProxySession = new _wkConnection.WKSession(this._connection, pageProxyId, `Target closed`, message => {130 this._connection.rawSend({ ...message,131 pageProxyId132 });133 });134 const opener = event.openerId ? this._wkPages.get(event.openerId) : undefined;135 const wkPage = new _wkPage.WKPage(context, pageProxySession, opener || null);136 this._wkPages.set(pageProxyId, wkPage);137 }138 _onPageProxyDestroyed(event) {139 const pageProxyId = event.pageProxyId;140 const wkPage = this._wkPages.get(pageProxyId);141 if (!wkPage) return;142 wkPage.didClose();143 wkPage.dispose(false);144 this._wkPages.delete(pageProxyId);145 }146 _onPageProxyMessageReceived(event) {147 const wkPage = this._wkPages.get(event.pageProxyId);148 if (!wkPage) return;149 wkPage.dispatchMessageToSession(event.message);150 }151 _onProvisionalLoadFailed(event) {152 const wkPage = this._wkPages.get(event.pageProxyId);153 if (!wkPage) return;154 wkPage.handleProvisionalLoadFailed(event);155 }156 _onWindowOpen(event) {157 const wkPage = this._wkPages.get(event.pageProxyId);158 if (!wkPage) return;159 wkPage.handleWindowOpen(event);160 }161 isConnected() {162 return !this._connection.isClosed();163 }164}165exports.WKBrowser = WKBrowser;166class WKBrowserContext extends _browserContext.BrowserContext {167 constructor(browser, browserContextId, options) {168 super(browser, options, browserContextId);169 this._evaluateOnNewDocumentSources = void 0;170 this._evaluateOnNewDocumentSources = [];171 this._authenticateProxyViaHeader();172 }173 async _initialize() {174 (0, _utils.assert)(!this._wkPages().length);175 const browserContextId = this._browserContextId;176 const promises = [super._initialize()];177 promises.push(this._browser._browserSession.send('Playwright.setDownloadBehavior', {178 behavior: this._options.acceptDownloads ? 'allow' : 'deny',179 downloadPath: this._browser.options.downloadsPath,180 browserContextId181 }));182 if (this._options.ignoreHTTPSErrors) promises.push(this._browser._browserSession.send('Playwright.setIgnoreCertificateErrors', {183 browserContextId,184 ignore: true185 }));186 if (this._options.locale) promises.push(this._browser._browserSession.send('Playwright.setLanguages', {187 browserContextId,188 languages: [this._options.locale]189 }));190 if (this._options.permissions) promises.push(this.grantPermissions(this._options.permissions));191 if (this._options.geolocation) promises.push(this.setGeolocation(this._options.geolocation));192 if (this._options.offline) promises.push(this.setOffline(this._options.offline));193 if (this._options.httpCredentials) promises.push(this.setHTTPCredentials(this._options.httpCredentials));194 await Promise.all(promises);195 }196 _wkPages() {197 return Array.from(this._browser._wkPages.values()).filter(wkPage => wkPage._browserContext === this);198 }199 pages() {200 return this._wkPages().map(wkPage => wkPage._initializedPage).filter(pageOrNull => !!pageOrNull);201 }202 async newPageDelegate() {203 (0, _browserContext.assertBrowserContextIsNotOwned)(this);204 const {205 pageProxyId206 } = await this._browser._browserSession.send('Playwright.createPage', {207 browserContextId: this._browserContextId208 });209 return this._browser._wkPages.get(pageProxyId);210 }211 async _doCookies(urls) {212 const {213 cookies214 } = await this._browser._browserSession.send('Playwright.getAllCookies', {215 browserContextId: this._browserContextId216 });217 return network.filterCookies(cookies.map(c => {218 const copy = { ...c219 };220 copy.expires = c.expires === -1 ? -1 : c.expires / 1000;221 delete copy.session;222 return copy;223 }), urls);224 }225 async addCookies(cookies) {226 const cc = network.rewriteCookies(cookies).map(c => ({ ...c,227 session: c.expires === -1 || c.expires === undefined,228 expires: c.expires && c.expires !== -1 ? c.expires * 1000 : c.expires229 }));230 await this._browser._browserSession.send('Playwright.setCookies', {231 cookies: cc,232 browserContextId: this._browserContextId233 });234 }235 async clearCookies() {236 await this._browser._browserSession.send('Playwright.deleteAllCookies', {237 browserContextId: this._browserContextId238 });239 }240 async _doGrantPermissions(origin, permissions) {241 await Promise.all(this.pages().map(page => page._delegate._grantPermissions(origin, permissions)));242 }243 async _doClearPermissions() {244 await Promise.all(this.pages().map(page => page._delegate._clearPermissions()));245 }246 async setGeolocation(geolocation) {247 (0, _browserContext.verifyGeolocation)(geolocation);248 this._options.geolocation = geolocation;249 const payload = geolocation ? { ...geolocation,250 timestamp: Date.now()251 } : undefined;252 await this._browser._browserSession.send('Playwright.setGeolocationOverride', {253 browserContextId: this._browserContextId,254 geolocation: payload255 });256 }257 async setExtraHTTPHeaders(headers) {258 this._options.extraHTTPHeaders = headers;259 for (const page of this.pages()) await page._delegate.updateExtraHTTPHeaders();260 }261 async setOffline(offline) {262 this._options.offline = offline;263 for (const page of this.pages()) await page._delegate.updateOffline();264 }265 async _doSetHTTPCredentials(httpCredentials) {266 this._options.httpCredentials = httpCredentials;267 for (const page of this.pages()) await page._delegate.updateHttpCredentials();268 }269 async _doAddInitScript(source) {270 this._evaluateOnNewDocumentSources.push(source);271 for (const page of this.pages()) await page._delegate._updateBootstrapScript();272 }273 async _doExposeBinding(binding) {274 for (const page of this.pages()) await page._delegate.exposeBinding(binding);275 }276 async _doUpdateRequestInterception() {277 for (const page of this.pages()) await page._delegate.updateRequestInterception();278 }279 _onClosePersistent() {}280 async _doClose() {281 (0, _utils.assert)(this._browserContextId);282 await this._browser._browserSession.send('Playwright.deleteContext', {283 browserContextId: this._browserContextId284 });285 this._browser._contexts.delete(this._browserContextId);286 }287 async _doCancelDownload(uuid) {288 await this._browser._browserSession.send('Playwright.cancelDownload', {289 uuid290 });291 }292}...
Using AI Code Generation
1const { assertBrowserContextIsNotOwned } = require('playwright/lib/server/browserContext');2const { assertBrowserIsNotOwned } = require('playwright/lib/server/browser');3const { assertPageIsNotOwned } = require('playwright/lib/server/page');4assertBrowserContextIsNotOwned(context);5assertBrowserIsNotOwned(browser);6assertPageIsNotOwned(page);7assertBrowserContextIsNotOwned(context);8assertBrowserIsNotOwned(browser);9assertPageIsNotOwned(page);10assertBrowserContextIsNotOwned(context);11assertBrowserIsNotOwned(browser);12assertPageIsNotOwned(page);13assertBrowserContextIsNotOwned(context);14assertBrowserIsNotOwned(browser);15assertPageIsNotOwned(page);16assertBrowserContextIsNotOwned(context);17assertBrowserIsNotOwned(browser);18assertPageIsNotOwned(page);19assertBrowserContextIsNotOwned(context);20assertBrowserIsNotOwned(browser);21assertPageIsNotOwned(page);22assertBrowserContextIsNotOwned(context);23assertBrowserIsNotOwned(browser);24assertPageIsNotOwned(page);25assertBrowserContextIsNotOwned(context);26assertBrowserIsNotOwned(browser);27assertPageIsNotOwned(page);28assertBrowserContextIsNotOwned(context);29assertBrowserIsNotOwned(browser);30assertPageIsNotOwned(page);31assertBrowserContextIsNotOwned(context);32assertBrowserIsNotOwned(browser);33assertPageIsNotOwned(page);34assertBrowserContextIsNotOwned(context);35assertBrowserIsNotOwned(browser);36assertPageIsNotOwned(page);
Using AI Code Generation
1const { assertBrowserContextIsNotOwned } = require('playwright/lib/internal/frames');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 assertBrowserContextIsNotOwned(context);7 await context.close();8 await browser.close();9})();10 at assertBrowserContextIsNotOwned (/home/ashwin/playwright/test.js:3:3)11 at async Object.<anonymous> (/home/ashwin/playwright/test.js:10:3)12 at async ModuleJob.run (internal/modules/esm/module_job.js:152:23)13 at async Loader.import (internal/modules/esm/loader.js:166:24)14 at async Object.loadESM (internal/process/esm_loader.js:68:5)
Using AI Code Generation
1const { assertBrowserContextIsNotOwned } = require('playwright/lib/server/browserContext');2assertBrowserContextIsNotOwned(context);3const { assertBrowserContextIsNotOwned } = require('playwright/lib/server/browserContext');4assertBrowserContextIsNotOwned(context);5const context = page.context();6const page = context.pages()[0];7const browser = context.browser();8I'm not sure what you want to do. If you want to get the browser context, you can do: const context = page.context(); If you want to get the page, you can do: const page = context.pages()[0]; If you want to get the browser, you can do: const browser = context.browser();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright['chromium'].launch();4 const context = await browser.newContext();5 await context.close();6 await browser.close();7})();8const playwright = require('playwright');9(async () => {10 const browser = await playwright['chromium'].launch();11 await browser.close();12})();13const playwright = require('playwright');14(async () => {15 const browser = await playwright['chromium'].launch();16 const context = await browser.newContext();17 await context.close();18 await browser.close();19})();20const playwright = require('playwright');21(async () => {22 const browser = await playwright['chromium'].launch();23 await browser.close();24})();25const playwright = require('playwright');26(async () => {27 const browser = await playwright['chromium'].launch();28 const context = await browser.newContext();29 await context.close();30 await browser.close();31})();32const playwright = require('playwright');33(async () => {34 const browser = await playwright['chromium'].launch();35 await browser.close();36})();37const playwright = require('playwright');38(async () => {39 const browser = await playwright['chromium'].launch();40 const context = await browser.newContext();41 await context.close();42 await browser.close();43})();44const playwright = require('playwright');45(async () => {46 const browser = await playwright['chromium'].launch();47 await browser.close();48})();49const playwright = require('playwright');50(async () => {51 const browser = await playwright['chromium'].launch();52 const context = await browser.newContext();53 await context.close();54 await browser.close();55})();56const playwright = require('playwright');
Using AI Code Generation
1const { assertBrowserContextIsNotOwned } = require('playwright/lib/server/browserContext');2assertBrowserContextIsNotOwned(context);3const browser = await chromium.launch({ headless: false, slowMo: 50 });4const context = await browser.newContext();5await context.close();6await browser.close();
Using AI Code Generation
1const assertBrowserContextIsNotOwned = require('playwright-core/lib/utils/internal-utils').assertBrowserContextIsNotOwned;2const playwright = require('playwright-core');3const browser = await playwright.chromium.launch({headless: false});4const context = await browser.newContext();5const page = await context.newPage();6await page.close();7await context.close();8await browser.close();9const assertBrowserContextIsOwned = require('playwright-core/lib/utils/internal-utils').assertBrowserContextIsOwned;10const playwright = require('playwright-core');11const browser = await playwright.chromium.launch({headless: false});12const context = await browser.newContext();13const page = await context.newPage();14await page.close();15await context.close();16await browser.close();17const assertBrowserIsNotOwned = require('playwright-core/lib/utils/internal-utils').assertBrowserIsNotOwned;18const playwright = require('playwright-core');19const browser = await playwright.chromium.launch({headless: false});20const context = await browser.newContext();21const page = await context.newPage();22await page.close();23await context.close();24await browser.close();25const assertBrowserIsOwned = require('playwright-core/lib/utils/internal-utils').assertBrowserIsOwned;26const playwright = require('playwright-core');27const browser = await playwright.chromium.launch({headless: false});28const context = await browser.newContext();29const page = await context.newPage();
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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!!