Best JavaScript code snippet using playwright-internal
TargetRegistry.js
Source:TargetRegistry.js
...450 }451 async ensurePermissions() {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 = [];...
ffPage.js
Source:ffPage.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.UTILITY_WORLD_NAME = exports.FFPage = void 0;6var dialog = _interopRequireWildcard(require("../dialog"));7var dom = _interopRequireWildcard(require("../dom"));8var _eventsHelper = require("../../utils/eventsHelper");9var _utils = require("../../utils");10var _page = require("../page");11var _ffAccessibility = require("./ffAccessibility");12var _ffConnection = require("./ffConnection");13var _ffExecutionContext = require("./ffExecutionContext");14var _ffInput = require("./ffInput");15var _ffNetworkManager = require("./ffNetworkManager");16var _stackTrace = require("../../utils/stackTrace");17var _debugLogger = require("../../common/debugLogger");18var _manualPromise = require("../../utils/manualPromise");19function _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); }20function _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; }21/**22 * Copyright 2019 Google Inc. All rights reserved.23 * Modifications copyright (c) Microsoft Corporation.24 *25 * Licensed under the Apache License, Version 2.0 (the "License");26 * you may not use this file except in compliance with the License.27 * You may obtain a copy of the License at28 *29 * http://www.apache.org/licenses/LICENSE-2.030 *31 * Unless required by applicable law or agreed to in writing, software32 * distributed under the License is distributed on an "AS IS" BASIS,33 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.34 * See the License for the specific language governing permissions and35 * limitations under the License.36 */37const UTILITY_WORLD_NAME = '__playwright_utility_world__';38exports.UTILITY_WORLD_NAME = UTILITY_WORLD_NAME;39class FFPage {40 constructor(session, browserContext, opener) {41 this.cspErrorsAsynchronousForInlineScipts = true;42 this.rawMouse = void 0;43 this.rawKeyboard = void 0;44 this.rawTouchscreen = void 0;45 this._session = void 0;46 this._page = void 0;47 this._networkManager = void 0;48 this._browserContext = void 0;49 this._pagePromise = new _manualPromise.ManualPromise();50 this._initializedPage = null;51 this._initializationFailed = false;52 this._opener = void 0;53 this._contextIdToContext = void 0;54 this._eventListeners = void 0;55 this._workers = new Map();56 this._screencastId = void 0;57 this._initScripts = [];58 this._session = session;59 this._opener = opener;60 this.rawKeyboard = new _ffInput.RawKeyboardImpl(session);61 this.rawMouse = new _ffInput.RawMouseImpl(session);62 this.rawTouchscreen = new _ffInput.RawTouchscreenImpl(session);63 this._contextIdToContext = new Map();64 this._browserContext = browserContext;65 this._page = new _page.Page(this, browserContext);66 this.rawMouse.setPage(this._page);67 this._networkManager = new _ffNetworkManager.FFNetworkManager(session, this._page);68 this._page.on(_page.Page.Events.FrameDetached, frame => this._removeContextsForFrame(frame)); // TODO: remove Page.willOpenNewWindowAsynchronously from the protocol.69 this._eventListeners = [_eventsHelper.eventsHelper.addEventListener(this._session, 'Page.eventFired', this._onEventFired.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameAttached', this._onFrameAttached.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameDetached', this._onFrameDetached.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.navigationAborted', this._onNavigationAborted.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.navigationCommitted', this._onNavigationCommitted.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.navigationStarted', this._onNavigationStarted.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.sameDocumentNavigation', this._onSameDocumentNavigation.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Runtime.executionContextCreated', this._onExecutionContextCreated.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Runtime.executionContextDestroyed', this._onExecutionContextDestroyed.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.linkClicked', event => this._onLinkClicked(event.phase)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.uncaughtError', this._onUncaughtError.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Runtime.console', this._onConsole.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.dialogOpened', this._onDialogOpened.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.bindingCalled', this._onBindingCalled.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.fileChooserOpened', this._onFileChooserOpened.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.workerCreated', this._onWorkerCreated.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.workerDestroyed', this._onWorkerDestroyed.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.dispatchMessageFromWorker', this._onDispatchMessageFromWorker.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.crashed', this._onCrashed.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.videoRecordingStarted', this._onVideoRecordingStarted.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.webSocketCreated', this._onWebSocketCreated.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.webSocketClosed', this._onWebSocketClosed.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.webSocketFrameReceived', this._onWebSocketFrameReceived.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.webSocketFrameSent', this._onWebSocketFrameSent.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.screencastFrame', this._onScreencastFrame.bind(this))];70 session.once(_ffConnection.FFSessionEvents.Disconnected, () => {71 this._markAsError(new Error('Page closed'));72 this._page._didDisconnect();73 });74 this._session.once('Page.ready', async () => {75 await this._page.initOpener(this._opener);76 if (this._initializationFailed) return; // Note: it is important to call |reportAsNew| before resolving pageOrError promise,77 // so that anyone who awaits pageOrError got a ready and reported page.78 this._initializedPage = this._page;79 this._page.reportAsNew();80 this._pagePromise.resolve(this._page);81 }); // Ideally, we somehow ensure that utility world is created before Page.ready arrives, but currently it is racy.82 // Therefore, we can end up with an initialized page without utility world, although very unlikely.83 this.addInitScript('', UTILITY_WORLD_NAME).catch(e => this._markAsError(e));84 }85 potentiallyUninitializedPage() {86 return this._page;87 }88 async _markAsError(error) {89 // Same error may be report twice: channer disconnected and session.send fails.90 if (this._initializationFailed) return;91 this._initializationFailed = true;92 if (!this._initializedPage) {93 await this._page.initOpener(this._opener);94 this._page.reportAsNew(error);95 this._pagePromise.resolve(error);96 }97 }98 async pageOrError() {99 return this._pagePromise;100 }101 _onWebSocketCreated(event) {102 this._page._frameManager.onWebSocketCreated(webSocketId(event.frameId, event.wsid), event.requestURL);103 this._page._frameManager.onWebSocketRequest(webSocketId(event.frameId, event.wsid));104 }105 _onWebSocketClosed(event) {106 if (event.error) this._page._frameManager.webSocketError(webSocketId(event.frameId, event.wsid), event.error);107 this._page._frameManager.webSocketClosed(webSocketId(event.frameId, event.wsid));108 }109 _onWebSocketFrameReceived(event) {110 this._page._frameManager.webSocketFrameReceived(webSocketId(event.frameId, event.wsid), event.opcode, event.data);111 }112 _onWebSocketFrameSent(event) {113 this._page._frameManager.onWebSocketFrameSent(webSocketId(event.frameId, event.wsid), event.opcode, event.data);114 }115 _onExecutionContextCreated(payload) {116 const {117 executionContextId,118 auxData119 } = payload;120 const frame = this._page._frameManager.frame(auxData.frameId);121 if (!frame) return;122 const delegate = new _ffExecutionContext.FFExecutionContext(this._session, executionContextId);123 let worldName = null;124 if (auxData.name === UTILITY_WORLD_NAME) worldName = 'utility';else if (!auxData.name) worldName = 'main';125 const context = new dom.FrameExecutionContext(delegate, frame, worldName);126 context[contextDelegateSymbol] = delegate;127 if (worldName) frame._contextCreated(worldName, context);128 this._contextIdToContext.set(executionContextId, context);129 }130 _onExecutionContextDestroyed(payload) {131 const {132 executionContextId133 } = payload;134 const context = this._contextIdToContext.get(executionContextId);135 if (!context) return;136 this._contextIdToContext.delete(executionContextId);137 context.frame._contextDestroyed(context);138 }139 _removeContextsForFrame(frame) {140 for (const [contextId, context] of this._contextIdToContext) {141 if (context.frame === frame) this._contextIdToContext.delete(contextId);142 }143 }144 _onLinkClicked(phase) {145 if (phase === 'before') this._page._frameManager.frameWillPotentiallyRequestNavigation();else this._page._frameManager.frameDidPotentiallyRequestNavigation();146 }147 _onNavigationStarted(params) {148 this._page._frameManager.frameRequestedNavigation(params.frameId, params.navigationId);149 }150 _onNavigationAborted(params) {151 this._page._frameManager.frameAbortedNavigation(params.frameId, params.errorText, params.navigationId);152 }153 _onNavigationCommitted(params) {154 for (const [workerId, worker] of this._workers) {155 if (worker.frameId === params.frameId) this._onWorkerDestroyed({156 workerId157 });158 }159 this._page._frameManager.frameCommittedNewDocumentNavigation(params.frameId, params.url, params.name || '', params.navigationId || '', false);160 }161 _onSameDocumentNavigation(params) {162 this._page._frameManager.frameCommittedSameDocumentNavigation(params.frameId, params.url);163 }164 _onFrameAttached(params) {165 this._page._frameManager.frameAttached(params.frameId, params.parentFrameId);166 }167 _onFrameDetached(params) {168 this._page._frameManager.frameDetached(params.frameId);169 }170 _onEventFired(payload) {171 const {172 frameId,173 name174 } = payload;175 if (name === 'load') this._page._frameManager.frameLifecycleEvent(frameId, 'load');176 if (name === 'DOMContentLoaded') this._page._frameManager.frameLifecycleEvent(frameId, 'domcontentloaded');177 }178 _onUncaughtError(params) {179 const {180 name,181 message182 } = (0, _stackTrace.splitErrorMessage)(params.message);183 const error = new Error(message);184 error.stack = params.message + '\n' + params.stack.split('\n').filter(Boolean).map(a => a.replace(/([^@]*)@(.*)/, ' at $1 ($2)')).join('\n');185 error.name = name;186 this._page.firePageError(error);187 }188 _onConsole(payload) {189 const {190 type,191 args,192 executionContextId,193 location194 } = payload;195 const context = this._contextIdToContext.get(executionContextId);196 if (!context) return;197 this._page._addConsoleMessage(type, args.map(arg => context.createHandle(arg)), location);198 }199 _onDialogOpened(params) {200 this._page.emit(_page.Page.Events.Dialog, new dialog.Dialog(this._page, params.type, params.message, async (accept, promptText) => {201 await this._session.sendMayFail('Page.handleDialog', {202 dialogId: params.dialogId,203 accept,204 promptText205 });206 }, params.defaultValue));207 }208 async _onBindingCalled(event) {209 const pageOrError = await this.pageOrError();210 if (!(pageOrError instanceof Error)) {211 const context = this._contextIdToContext.get(event.executionContextId);212 if (context) await this._page._onBindingCalled(event.payload, context);213 }214 }215 async _onFileChooserOpened(payload) {216 const {217 executionContextId,218 element219 } = payload;220 const context = this._contextIdToContext.get(executionContextId);221 if (!context) return;222 const handle = context.createHandle(element).asElement();223 await this._page._onFileChooserOpened(handle);224 }225 async _onWorkerCreated(event) {226 const workerId = event.workerId;227 const worker = new _page.Worker(this._page, event.url);228 const workerSession = new _ffConnection.FFSession(this._session._connection, workerId, message => {229 this._session.send('Page.sendMessageToWorker', {230 frameId: event.frameId,231 workerId: workerId,232 message: JSON.stringify(message)233 }).catch(e => {234 workerSession.dispatchMessage({235 id: message.id,236 method: '',237 params: {},238 error: {239 message: e.message,240 data: undefined241 }242 });243 });244 });245 this._workers.set(workerId, {246 session: workerSession,247 frameId: event.frameId248 });249 this._page._addWorker(workerId, worker);250 workerSession.once('Runtime.executionContextCreated', event => {251 worker._createExecutionContext(new _ffExecutionContext.FFExecutionContext(workerSession, event.executionContextId));252 });253 workerSession.on('Runtime.console', event => {254 const {255 type,256 args,257 location258 } = event;259 const context = worker._existingExecutionContext;260 this._page._addConsoleMessage(type, args.map(arg => context.createHandle(arg)), location);261 }); // Note: we receive worker exceptions directly from the page.262 }263 _onWorkerDestroyed(event) {264 const workerId = event.workerId;265 const worker = this._workers.get(workerId);266 if (!worker) return;267 worker.session.dispose();268 this._workers.delete(workerId);269 this._page._removeWorker(workerId);270 }271 async _onDispatchMessageFromWorker(event) {272 const worker = this._workers.get(event.workerId);273 if (!worker) return;274 worker.session.dispatchMessage(JSON.parse(event.message));275 }276 async _onCrashed(event) {277 this._session.markAsCrashed();278 this._page._didCrash();279 }280 _onVideoRecordingStarted(event) {281 this._browserContext._browser._videoStarted(this._browserContext, event.screencastId, event.file, this.pageOrError());282 }283 async exposeBinding(binding) {284 await this._session.send('Page.addBinding', {285 name: binding.name,286 script: binding.source287 });288 }289 async removeExposedBindings() {// TODO: implement me.290 }291 didClose() {292 this._session.dispose();293 _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);294 this._networkManager.dispose();295 this._page._didClose();296 }297 async navigateFrame(frame, url, referer) {298 const response = await this._session.send('Page.navigate', {299 url,300 referer,301 frameId: frame._id302 });303 return {304 newDocumentId: response.navigationId || undefined305 };306 }307 async updateExtraHTTPHeaders() {308 await this._session.send('Network.setExtraHTTPHeaders', {309 headers: this._page._state.extraHTTPHeaders || []310 });311 }312 async setEmulatedSize(emulatedSize) {313 (0, _utils.assert)(this._page._state.emulatedSize === emulatedSize);314 await this._session.send('Page.setViewportSize', {315 viewportSize: {316 width: emulatedSize.viewport.width,317 height: emulatedSize.viewport.height318 }319 });320 }321 async bringToFront() {322 await this._session.send('Page.bringToFront', {});323 }324 async updateEmulateMedia() {325 const colorScheme = this._page._state.colorScheme === null ? undefined : this._page._state.colorScheme;326 const reducedMotion = this._page._state.reducedMotion === null ? undefined : this._page._state.reducedMotion;327 const forcedColors = this._page._state.forcedColors === null ? undefined : this._page._state.forcedColors;328 await this._session.send('Page.setEmulatedMedia', {329 // Empty string means reset.330 type: this._page._state.mediaType === null ? '' : this._page._state.mediaType,331 colorScheme,332 reducedMotion,333 forcedColors334 });335 }336 async updateRequestInterception() {337 await this._networkManager.setRequestInterception(this._page._needsRequestInterception());338 }339 async setFileChooserIntercepted(enabled) {340 await this._session.send('Page.setInterceptFileChooserDialog', {341 enabled342 }).catch(e => {}); // target can be closed.343 }344 async reload() {345 await this._session.send('Page.reload', {346 frameId: this._page.mainFrame()._id347 });348 }349 async goBack() {350 const {351 success352 } = await this._session.send('Page.goBack', {353 frameId: this._page.mainFrame()._id354 });355 return success;356 }357 async goForward() {358 const {359 success360 } = await this._session.send('Page.goForward', {361 frameId: this._page.mainFrame()._id362 });363 return success;364 }365 async addInitScript(script, worldName) {366 this._initScripts.push({367 script,368 worldName369 });370 await this._session.send('Page.setInitScripts', {371 scripts: this._initScripts372 });373 }374 async removeInitScripts() {375 this._initScripts = [];376 await this._session.send('Page.setInitScripts', {377 scripts: []378 });379 }380 async closePage(runBeforeUnload) {381 await this._session.send('Page.close', {382 runBeforeUnload383 });384 }385 async setBackgroundColor(color) {386 if (color) throw new Error('Not implemented');387 }388 async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport, scale) {389 if (!documentRect) {390 const scrollOffset = await this._page.mainFrame().waitForFunctionValueInUtility(progress, () => ({391 x: window.scrollX,392 y: window.scrollY393 }));394 documentRect = {395 x: viewportRect.x + scrollOffset.x,396 y: viewportRect.y + scrollOffset.y,397 width: viewportRect.width,398 height: viewportRect.height399 };400 } // TODO: remove fullPage option from Page.screenshot.401 // TODO: remove Page.getBoundingBox method.402 progress.throwIfAborted();403 const {404 data405 } = await this._session.send('Page.screenshot', {406 mimeType: 'image/' + format,407 clip: documentRect,408 omitDeviceScaleFactor: scale === 'css'409 });410 return Buffer.from(data, 'base64');411 }412 async getContentFrame(handle) {413 const {414 contentFrameId415 } = await this._session.send('Page.describeNode', {416 frameId: handle._context.frame._id,417 objectId: handle._objectId418 });419 if (!contentFrameId) return null;420 return this._page._frameManager.frame(contentFrameId);421 }422 async getOwnerFrame(handle) {423 const {424 ownerFrameId425 } = await this._session.send('Page.describeNode', {426 frameId: handle._context.frame._id,427 objectId: handle._objectId428 });429 return ownerFrameId || null;430 }431 isElementHandle(remoteObject) {432 return remoteObject.subtype === 'node';433 }434 async getBoundingBox(handle) {435 const quads = await this.getContentQuads(handle);436 if (!quads || !quads.length) return null;437 let minX = Infinity;438 let maxX = -Infinity;439 let minY = Infinity;440 let maxY = -Infinity;441 for (const quad of quads) {442 for (const point of quad) {443 minX = Math.min(minX, point.x);444 maxX = Math.max(maxX, point.x);445 minY = Math.min(minY, point.y);446 maxY = Math.max(maxY, point.y);447 }448 }449 return {450 x: minX,451 y: minY,452 width: maxX - minX,453 height: maxY - minY454 };455 }456 async scrollRectIntoViewIfNeeded(handle, rect) {457 return await this._session.send('Page.scrollIntoViewIfNeeded', {458 frameId: handle._context.frame._id,459 objectId: handle._objectId,460 rect461 }).then(() => 'done').catch(e => {462 if (e instanceof Error && e.message.includes('Node is detached from document')) return 'error:notconnected';463 if (e instanceof Error && e.message.includes('Node does not have a layout object')) return 'error:notvisible';464 throw e;465 });466 }467 async setScreencastOptions(options) {468 if (options) {469 const {470 screencastId471 } = await this._session.send('Page.startScreencast', options);472 this._screencastId = screencastId;473 } else {474 await this._session.send('Page.stopScreencast');475 }476 }477 _onScreencastFrame(event) {478 if (!this._screencastId) return;479 const screencastId = this._screencastId;480 this._page.throttleScreencastFrameAck(() => {481 this._session.send('Page.screencastFrameAck', {482 screencastId483 }).catch(e => _debugLogger.debugLogger.log('error', e));484 });485 const buffer = Buffer.from(event.data, 'base64');486 this._page.emit(_page.Page.Events.ScreencastFrame, {487 buffer,488 width: event.deviceWidth,489 height: event.deviceHeight490 });491 }492 rafCountForStablePosition() {493 return 1;494 }495 async getContentQuads(handle) {496 const result = await this._session.sendMayFail('Page.getContentQuads', {497 frameId: handle._context.frame._id,498 objectId: handle._objectId499 });500 if (!result) return null;501 return result.quads.map(quad => [quad.p1, quad.p2, quad.p3, quad.p4]);502 }503 async setInputFiles(handle, files) {504 await handle.evaluateInUtility(([injected, node, files]) => injected.setInputFiles(node, files), files);505 }506 async setInputFilePaths(handle, files) {507 await Promise.all([this._session.send('Page.setFileInputFiles', {508 frameId: handle._context.frame._id,509 objectId: handle._objectId,510 files511 }), handle.dispatchEvent('input'), handle.dispatchEvent('change')]);512 }513 async adoptElementHandle(handle, to) {514 const result = await this._session.send('Page.adoptNode', {515 frameId: handle._context.frame._id,516 objectId: handle._objectId,517 executionContextId: to[contextDelegateSymbol]._executionContextId518 });519 if (!result.remoteObject) throw new Error(dom.kUnableToAdoptErrorMessage);520 return to.createHandle(result.remoteObject);521 }522 async getAccessibilityTree(needle) {523 return (0, _ffAccessibility.getAccessibilityTree)(this._session, needle);524 }525 async inputActionEpilogue() {}526 async getFrameElement(frame) {527 const parent = frame.parentFrame();528 if (!parent) throw new Error('Frame has been detached.');529 const info = this._page.parseSelector('frame,iframe');530 const handles = await this._page.selectors._queryAll(parent, info);531 const items = await Promise.all(handles.map(async handle => {532 const frame = await handle.contentFrame().catch(e => null);533 return {534 handle,535 frame536 };537 }));538 const result = items.find(item => item.frame === frame);539 items.map(item => item === result ? Promise.resolve() : item.handle.dispose());540 if (!result) throw new Error('Frame has been detached.');541 return result.handle;542 }543}544exports.FFPage = FFPage;545function webSocketId(frameId, wsid) {546 return `${frameId}---${wsid}`;547}...
Protocol.js
Source:Protocol.js
1/* This Source Code Form is subject to the terms of the Mozilla Public2 * License, v. 2.0. If a copy of the MPL was not distributed with this3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */4const {t, checkScheme} = ChromeUtils.import('chrome://juggler/content/protocol/PrimitiveTypes.js');5// Protocol-specific types.6const browserTypes = {};7browserTypes.TargetInfo = {8 type: t.Enum(['page']),9 targetId: t.String,10 browserContextId: t.Optional(t.String),11 // PageId of parent tab, if any.12 openerId: t.Optional(t.String),13};14browserTypes.CookieOptions = {15 name: t.String,16 value: t.String,17 url: t.Optional(t.String),18 domain: t.Optional(t.String),19 path: t.Optional(t.String),20 secure: t.Optional(t.Boolean),21 httpOnly: t.Optional(t.Boolean),22 sameSite: t.Optional(t.Enum(['Strict', 'Lax', 'None'])),23 expires: t.Optional(t.Number),24};25browserTypes.Cookie = {26 name: t.String,27 domain: t.String,28 path: t.String,29 value: t.String,30 expires: t.Number,31 size: t.Number,32 httpOnly: t.Boolean,33 secure: t.Boolean,34 session: t.Boolean,35 sameSite: t.Enum(['Strict', 'Lax', 'None']),36};37browserTypes.Geolocation = {38 latitude: t.Number,39 longitude: t.Number,40 accuracy: t.Optional(t.Number),41};42browserTypes.DownloadOptions = {43 behavior: t.Optional(t.Enum(['saveToDisk', 'cancel'])),44 downloadsDir: t.Optional(t.String),45};46const pageTypes = {};47pageTypes.DOMPoint = {48 x: t.Number,49 y: t.Number,50};51pageTypes.Rect = {52 x: t.Number,53 y: t.Number,54 width: t.Number,55 height: t.Number,56};57pageTypes.Size = {58 width: t.Number,59 height: t.Number,60};61pageTypes.Viewport = {62 viewportSize: pageTypes.Size,63 deviceScaleFactor: t.Optional(t.Number),64};65pageTypes.DOMQuad = {66 p1: pageTypes.DOMPoint,67 p2: pageTypes.DOMPoint,68 p3: pageTypes.DOMPoint,69 p4: pageTypes.DOMPoint,70};71pageTypes.TouchPoint = {72 x: t.Number,73 y: t.Number,74 radiusX: t.Optional(t.Number),75 radiusY: t.Optional(t.Number),76 rotationAngle: t.Optional(t.Number),77 force: t.Optional(t.Number),78};79pageTypes.Clip = {80 x: t.Number,81 y: t.Number,82 width: t.Number,83 height: t.Number,84};85pageTypes.InitScript = {86 script: t.String,87 worldName: t.Optional(t.String),88};89const runtimeTypes = {};90runtimeTypes.RemoteObject = {91 type: t.Optional(t.Enum(['object', 'function', 'undefined', 'string', 'number', 'boolean', 'symbol', 'bigint'])),92 subtype: t.Optional(t.Enum(['array', 'null', 'node', 'regexp', 'date', 'map', 'set', 'weakmap', 'weakset', 'error', 'proxy', 'promise', 'typedarray'])),93 objectId: t.Optional(t.String),94 unserializableValue: t.Optional(t.Enum(['Infinity', '-Infinity', '-0', 'NaN'])),95 value: t.Any96};97runtimeTypes.ObjectProperty = {98 name: t.String,99 value: runtimeTypes.RemoteObject,100};101runtimeTypes.ScriptLocation = {102 columnNumber: t.Number,103 lineNumber: t.Number,104 url: t.String,105};106runtimeTypes.ExceptionDetails = {107 text: t.Optional(t.String),108 stack: t.Optional(t.String),109 value: t.Optional(t.Any),110};111runtimeTypes.CallFunctionArgument = {112 objectId: t.Optional(t.String),113 unserializableValue: t.Optional(t.Enum(['Infinity', '-Infinity', '-0', 'NaN'])),114 value: t.Any,115};116runtimeTypes.AuxData = {117 frameId: t.Optional(t.String),118 name: t.Optional(t.String),119};120const axTypes = {};121axTypes.AXTree = {122 role: t.String,123 name: t.String,124 children: t.Optional(t.Array(t.Recursive(axTypes, 'AXTree'))),125 selected: t.Optional(t.Boolean),126 focused: t.Optional(t.Boolean),127 pressed: t.Optional(t.Boolean),128 focusable: t.Optional(t.Boolean),129 haspopup: t.Optional(t.Boolean),130 required: t.Optional(t.Boolean),131 invalid: t.Optional(t.Boolean),132 modal: t.Optional(t.Boolean),133 editable: t.Optional(t.Boolean),134 busy: t.Optional(t.Boolean),135 multiline: t.Optional(t.Boolean),136 readonly: t.Optional(t.Boolean),137 checked: t.Optional(t.Enum(['mixed', true])),138 expanded: t.Optional(t.Boolean),139 disabled: t.Optional(t.Boolean),140 multiselectable: t.Optional(t.Boolean),141 value: t.Optional(t.String),142 description: t.Optional(t.String),143 roledescription: t.Optional(t.String),144 valuetext: t.Optional(t.String),145 orientation: t.Optional(t.String),146 autocomplete: t.Optional(t.String),147 keyshortcuts: t.Optional(t.String),148 level: t.Optional(t.Number),149 tag: t.Optional(t.String),150 foundObject: t.Optional(t.Boolean),151}152const networkTypes = {};153networkTypes.HTTPHeader = {154 name: t.String,155 value: t.String,156};157networkTypes.HTTPCredentials = {158 username: t.String,159 password: t.String,160};161networkTypes.SecurityDetails = {162 protocol: t.String,163 subjectName: t.String,164 issuer: t.String,165 validFrom: t.Number,166 validTo: t.Number,167};168networkTypes.ResourceTiming = {169 startTime: t.Number,170 domainLookupStart: t.Number,171 domainLookupEnd: t.Number,172 connectStart: t.Number,173 secureConnectionStart: t.Number,174 connectEnd: t.Number,175 requestStart: t.Number,176 responseStart: t.Number,177};178const Browser = {179 targets: ['browser'],180 types: browserTypes,181 events: {182 'attachedToTarget': {183 sessionId: t.String,184 targetInfo: browserTypes.TargetInfo,185 },186 'detachedFromTarget': {187 sessionId: t.String,188 targetId: t.String,189 },190 'downloadCreated': {191 uuid: t.String,192 browserContextId: t.Optional(t.String),193 pageTargetId: t.String,194 url: t.String,195 suggestedFileName: t.String,196 },197 'downloadFinished': {198 uuid: t.String,199 canceled: t.Optional(t.Boolean),200 error: t.Optional(t.String),201 },202 'videoRecordingFinished': {203 screencastId: t.String,204 },205 },206 methods: {207 'enable': {208 params: {209 attachToDefaultContext: t.Boolean,210 },211 },212 'createBrowserContext': {213 params: {214 removeOnDetach: t.Optional(t.Boolean),215 },216 returns: {217 browserContextId: t.String,218 },219 },220 'removeBrowserContext': {221 params: {222 browserContextId: t.String,223 },224 },225 'newPage': {226 params: {227 browserContextId: t.Optional(t.String),228 },229 returns: {230 targetId: t.String,231 }232 },233 'close': {},234 'getInfo': {235 returns: {236 userAgent: t.String,237 version: t.String,238 },239 },240 'setExtraHTTPHeaders': {241 params: {242 browserContextId: t.Optional(t.String),243 headers: t.Array(networkTypes.HTTPHeader),244 },245 },246 'setBrowserProxy': {247 params: {248 type: t.Enum(['http', 'https', 'socks', 'socks4']),249 bypass: t.Array(t.String),250 host: t.String,251 port: t.Number,252 username: t.Optional(t.String),253 password: t.Optional(t.String),254 },255 },256 'setContextProxy': {257 params: {258 browserContextId: t.Optional(t.String),259 type: t.Enum(['http', 'https', 'socks', 'socks4']),260 bypass: t.Array(t.String),261 host: t.String,262 port: t.Number,263 username: t.Optional(t.String),264 password: t.Optional(t.String),265 },266 },267 'setHTTPCredentials': {268 params: {269 browserContextId: t.Optional(t.String),270 credentials: t.Nullable(networkTypes.HTTPCredentials),271 },272 },273 'setRequestInterception': {274 params: {275 browserContextId: t.Optional(t.String),276 enabled: t.Boolean,277 },278 },279 'setGeolocationOverride': {280 params: {281 browserContextId: t.Optional(t.String),282 geolocation: t.Nullable(browserTypes.Geolocation),283 }284 },285 'setUserAgentOverride': {286 params: {287 browserContextId: t.Optional(t.String),288 userAgent: t.Nullable(t.String),289 }290 },291 'setPlatformOverride': {292 params: {293 browserContextId: t.Optional(t.String),294 platform: t.Nullable(t.String),295 }296 },297 'setBypassCSP': {298 params: {299 browserContextId: t.Optional(t.String),300 bypassCSP: t.Nullable(t.Boolean),301 }302 },303 'setIgnoreHTTPSErrors': {304 params: {305 browserContextId: t.Optional(t.String),306 ignoreHTTPSErrors: t.Nullable(t.Boolean),307 }308 },309 'setJavaScriptDisabled': {310 params: {311 browserContextId: t.Optional(t.String),312 javaScriptDisabled: t.Boolean,313 }314 },315 'setLocaleOverride': {316 params: {317 browserContextId: t.Optional(t.String),318 locale: t.Nullable(t.String),319 }320 },321 'setTimezoneOverride': {322 params: {323 browserContextId: t.Optional(t.String),324 timezoneId: t.Nullable(t.String),325 }326 },327 'setDownloadOptions': {328 params: {329 browserContextId: t.Optional(t.String),330 downloadOptions: t.Nullable(browserTypes.DownloadOptions),331 }332 },333 'setTouchOverride': {334 params: {335 browserContextId: t.Optional(t.String),336 hasTouch: t.Nullable(t.Boolean),337 }338 },339 'setDefaultViewport': {340 params: {341 browserContextId: t.Optional(t.String),342 viewport: t.Nullable(pageTypes.Viewport),343 }344 },345 'setScrollbarsHidden': {346 params: {347 browserContextId: t.Optional(t.String),348 hidden: t.Boolean,349 }350 },351 'setInitScripts': {352 params: {353 browserContextId: t.Optional(t.String),354 scripts: t.Array(pageTypes.InitScript),355 }356 },357 'addBinding': {358 params: {359 browserContextId: t.Optional(t.String),360 worldName: t.Optional(t.String),361 name: t.String,362 script: t.String,363 },364 },365 'grantPermissions': {366 params: {367 origin: t.String,368 browserContextId: t.Optional(t.String),369 permissions: t.Array(t.String),370 },371 },372 'resetPermissions': {373 params: {374 browserContextId: t.Optional(t.String),375 }376 },377 'setCookies': {378 params: {379 browserContextId: t.Optional(t.String),380 cookies: t.Array(browserTypes.CookieOptions),381 }382 },383 'clearCookies': {384 params: {385 browserContextId: t.Optional(t.String),386 }387 },388 'getCookies': {389 params: {390 browserContextId: t.Optional(t.String)391 },392 returns: {393 cookies: t.Array(browserTypes.Cookie),394 },395 },396 'setOnlineOverride': {397 params: {398 browserContextId: t.Optional(t.String),399 override: t.Nullable(t.Enum(['online', 'offline'])),400 }401 },402 'setColorScheme': {403 params: {404 browserContextId: t.Optional(t.String),405 colorScheme: t.Nullable(t.Enum(['dark', 'light', 'no-preference'])),406 },407 },408 'setReducedMotion': {409 params: {410 browserContextId: t.Optional(t.String),411 reducedMotion: t.Nullable(t.Enum(['reduce', 'no-preference'])),412 },413 },414 'setForcedColors': {415 params: {416 browserContextId: t.Optional(t.String),417 forcedColors: t.Nullable(t.Enum(['active', 'none'])),418 },419 },420 'setVideoRecordingOptions': {421 params: {422 browserContextId: t.Optional(t.String),423 options: t.Optional({424 dir: t.String,425 width: t.Number,426 height: t.Number,427 }),428 },429 },430 'cancelDownload': {431 params: {432 uuid: t.Optional(t.String),433 }434 }435 },436};437const Network = {438 targets: ['page'],439 types: networkTypes,440 events: {441 'requestWillBeSent': {442 // frameId may be absent for redirected requests.443 frameId: t.Optional(t.String),444 requestId: t.String,445 // RequestID of redirected request.446 redirectedFrom: t.Optional(t.String),447 postData: t.Optional(t.String),448 headers: t.Array(networkTypes.HTTPHeader),449 isIntercepted: t.Boolean,450 url: t.String,451 method: t.String,452 navigationId: t.Optional(t.String),453 cause: t.String,454 internalCause: t.String,455 },456 'responseReceived': {457 securityDetails: t.Nullable(networkTypes.SecurityDetails),458 requestId: t.String,459 fromCache: t.Boolean,460 remoteIPAddress: t.Optional(t.String),461 remotePort: t.Optional(t.Number),462 status: t.Number,463 statusText: t.String,464 headers: t.Array(networkTypes.HTTPHeader),465 timing: networkTypes.ResourceTiming,466 },467 'requestFinished': {468 requestId: t.String,469 responseEndTime: t.Number,470 transferSize: t.Number,471 encodedBodySize: t.Number,472 protocolVersion: t.Optional(t.String),473 },474 'requestFailed': {475 requestId: t.String,476 errorCode: t.String,477 },478 },479 methods: {480 'setRequestInterception': {481 params: {482 enabled: t.Boolean,483 },484 },485 'setExtraHTTPHeaders': {486 params: {487 headers: t.Array(networkTypes.HTTPHeader),488 },489 },490 'abortInterceptedRequest': {491 params: {492 requestId: t.String,493 errorCode: t.String,494 },495 },496 'resumeInterceptedRequest': {497 params: {498 requestId: t.String,499 url: t.Optional(t.String),500 method: t.Optional(t.String),501 headers: t.Optional(t.Array(networkTypes.HTTPHeader)),502 postData: t.Optional(t.String),503 },504 },505 'fulfillInterceptedRequest': {506 params: {507 requestId: t.String,508 status: t.Number,509 statusText: t.String,510 headers: t.Array(networkTypes.HTTPHeader),511 base64body: t.Optional(t.String), // base64-encoded512 },513 },514 'getResponseBody': {515 params: {516 requestId: t.String,517 },518 returns: {519 base64body: t.String,520 evicted: t.Optional(t.Boolean),521 },522 },523 },524};525const Runtime = {526 targets: ['page'],527 types: runtimeTypes,528 events: {529 'executionContextCreated': {530 executionContextId: t.String,531 auxData: runtimeTypes.AuxData,532 },533 'executionContextDestroyed': {534 executionContextId: t.String,535 },536 'console': {537 executionContextId: t.String,538 args: t.Array(runtimeTypes.RemoteObject),539 type: t.String,540 location: runtimeTypes.ScriptLocation,541 },542 },543 methods: {544 'evaluate': {545 params: {546 // Pass frameId here.547 executionContextId: t.String,548 expression: t.String,549 returnByValue: t.Optional(t.Boolean),550 },551 returns: {552 result: t.Optional(runtimeTypes.RemoteObject),553 exceptionDetails: t.Optional(runtimeTypes.ExceptionDetails),554 }555 },556 'callFunction': {557 params: {558 // Pass frameId here.559 executionContextId: t.String,560 functionDeclaration: t.String,561 returnByValue: t.Optional(t.Boolean),562 args: t.Array(runtimeTypes.CallFunctionArgument),563 },564 returns: {565 result: t.Optional(runtimeTypes.RemoteObject),566 exceptionDetails: t.Optional(runtimeTypes.ExceptionDetails),567 }568 },569 'disposeObject': {570 params: {571 executionContextId: t.String,572 objectId: t.String,573 },574 },575 'getObjectProperties': {576 params: {577 executionContextId: t.String,578 objectId: t.String,579 },580 returns: {581 properties: t.Array(runtimeTypes.ObjectProperty),582 }583 },584 },585};586const Page = {587 targets: ['page'],588 types: pageTypes,589 events: {590 'ready': {591 },592 'crashed': {593 },594 'eventFired': {595 frameId: t.String,596 name: t.Enum(['load', 'DOMContentLoaded']),597 },598 'uncaughtError': {599 frameId: t.String,600 message: t.String,601 stack: t.String,602 },603 'frameAttached': {604 frameId: t.String,605 parentFrameId: t.Optional(t.String),606 },607 'frameDetached': {608 frameId: t.String,609 },610 'navigationStarted': {611 frameId: t.String,612 navigationId: t.String,613 url: t.String,614 },615 'navigationCommitted': {616 frameId: t.String,617 // |navigationId| can only be null in response to enable.618 navigationId: t.Optional(t.String),619 url: t.String,620 // frame.id or frame.name621 name: t.String,622 },623 'navigationAborted': {624 frameId: t.String,625 navigationId: t.String,626 errorText: t.String,627 },628 'sameDocumentNavigation': {629 frameId: t.String,630 url: t.String,631 },632 'dialogOpened': {633 dialogId: t.String,634 type: t.Enum(['prompt', 'alert', 'confirm', 'beforeunload']),635 message: t.String,636 defaultValue: t.Optional(t.String),637 },638 'dialogClosed': {639 dialogId: t.String,640 },641 'bindingCalled': {642 executionContextId: t.String,643 name: t.String,644 payload: t.Any,645 },646 'linkClicked': {647 phase: t.Enum(['before', 'after']),648 },649 'willOpenNewWindowAsynchronously': {},650 'fileChooserOpened': {651 executionContextId: t.String,652 element: runtimeTypes.RemoteObject653 },654 'workerCreated': {655 workerId: t.String,656 frameId: t.String,657 url: t.String,658 },659 'workerDestroyed': {660 workerId: t.String,661 },662 'dispatchMessageFromWorker': {663 workerId: t.String,664 message: t.String,665 },666 'videoRecordingStarted': {667 screencastId: t.String,668 file: t.String,669 },670 'webSocketCreated': {671 frameId: t.String,672 wsid: t.String,673 requestURL: t.String,674 },675 'webSocketOpened': {676 frameId: t.String,677 requestId: t.String,678 wsid: t.String,679 effectiveURL: t.String,680 },681 'webSocketClosed': {682 frameId: t.String,683 wsid: t.String,684 error: t.String,685 },686 'webSocketFrameSent': {687 frameId: t.String,688 wsid: t.String,689 opcode: t.Number,690 data: t.String,691 },692 'webSocketFrameReceived': {693 frameId: t.String,694 wsid: t.String,695 opcode: t.Number,696 data: t.String,697 },698 'screencastFrame': {699 data: t.String,700 deviceWidth: t.Number,701 deviceHeight: t.Number,702 },703 },704 methods: {705 'close': {706 params: {707 runBeforeUnload: t.Optional(t.Boolean),708 },709 },710 'setFileInputFiles': {711 params: {712 frameId: t.String,713 objectId: t.String,714 files: t.Array(t.String),715 },716 },717 'addBinding': {718 params: {719 worldName: t.Optional(t.String),720 name: t.String,721 script: t.String,722 },723 },724 'setViewportSize': {725 params: {726 viewportSize: t.Nullable(pageTypes.Size),727 },728 },729 'bringToFront': {730 params: {731 },732 },733 'setEmulatedMedia': {734 params: {735 type: t.Optional(t.Enum(['screen', 'print', ''])),736 colorScheme: t.Optional(t.Enum(['dark', 'light', 'no-preference'])),737 reducedMotion: t.Optional(t.Enum(['reduce', 'no-preference'])),738 forcedColors: t.Optional(t.Enum(['active', 'none'])),739 },740 },741 'setCacheDisabled': {742 params: {743 cacheDisabled: t.Boolean,744 },745 },746 'describeNode': {747 params: {748 frameId: t.String,749 objectId: t.String,750 },751 returns: {752 contentFrameId: t.Optional(t.String),753 ownerFrameId: t.Optional(t.String),754 },755 },756 'scrollIntoViewIfNeeded': {757 params: {758 frameId: t.String,759 objectId: t.String,760 rect: t.Optional(pageTypes.Rect),761 },762 },763 'setInitScripts': {764 params: {765 scripts: t.Array(pageTypes.InitScript)766 }767 },768 'navigate': {769 params: {770 frameId: t.String,771 url: t.String,772 referer: t.Optional(t.String),773 },774 returns: {775 navigationId: t.Nullable(t.String),776 navigationURL: t.Nullable(t.String),777 }778 },779 'goBack': {780 params: {781 frameId: t.String,782 },783 returns: {784 success: t.Boolean,785 },786 },787 'goForward': {788 params: {789 frameId: t.String,790 },791 returns: {792 success: t.Boolean,793 },794 },795 'reload': {796 params: {797 frameId: t.String,798 },799 },800 'adoptNode': {801 params: {802 frameId: t.String,803 objectId: t.String,804 executionContextId: t.String,805 },806 returns: {807 remoteObject: t.Nullable(runtimeTypes.RemoteObject),808 },809 },810 'screenshot': {811 params: {812 mimeType: t.Enum(['image/png', 'image/jpeg']),813 clip: t.Optional(pageTypes.Clip),814 omitDeviceScaleFactor: t.Optional(t.Boolean),815 },816 returns: {817 data: t.String,818 }819 },820 'getContentQuads': {821 params: {822 frameId: t.String,823 objectId: t.String,824 },825 returns: {826 quads: t.Array(pageTypes.DOMQuad),827 },828 },829 'dispatchKeyEvent': {830 params: {831 type: t.String,832 key: t.String,833 keyCode: t.Number,834 location: t.Number,835 code: t.String,836 repeat: t.Boolean,837 text: t.Optional(t.String),838 }839 },840 'dispatchTouchEvent': {841 params: {842 type: t.Enum(['touchStart', 'touchEnd', 'touchMove', 'touchCancel']),843 touchPoints: t.Array(pageTypes.TouchPoint),844 modifiers: t.Number,845 },846 returns: {847 defaultPrevented: t.Boolean,848 }849 },850 'dispatchTapEvent': {851 params: {852 x: t.Number,853 y: t.Number,854 modifiers: t.Number,855 }856 },857 'dispatchMouseEvent': {858 params: {859 type: t.String,860 button: t.Number,861 x: t.Number,862 y: t.Number,863 modifiers: t.Number,864 clickCount: t.Optional(t.Number),865 buttons: t.Number,866 }867 },868 'dispatchWheelEvent': {869 params: {870 x: t.Number,871 y: t.Number,872 deltaX: t.Number,873 deltaY: t.Number,874 deltaZ: t.Number,875 modifiers: t.Number,876 }877 },878 'insertText': {879 params: {880 text: t.String,881 }882 },883 'crash': {884 params: {}885 },886 'handleDialog': {887 params: {888 dialogId: t.String,889 accept: t.Boolean,890 promptText: t.Optional(t.String),891 },892 },893 'setInterceptFileChooserDialog': {894 params: {895 enabled: t.Boolean,896 },897 },898 'sendMessageToWorker': {899 params: {900 frameId: t.String,901 workerId: t.String,902 message: t.String,903 },904 },905 'startScreencast': {906 params: {907 width: t.Number,908 height: t.Number,909 quality: t.Number,910 },911 returns: {912 screencastId: t.String,913 },914 },915 'screencastFrameAck': {916 params: {917 screencastId: t.String,918 },919 },920 'stopScreencast': {921 },922 },923};924const Accessibility = {925 targets: ['page'],926 types: axTypes,927 events: {},928 methods: {929 'getFullAXTree': {930 params: {931 objectId: t.Optional(t.String),932 },933 returns: {934 tree: axTypes.AXTree935 },936 }937 }938}939this.protocol = {940 domains: {Browser, Page, Runtime, Network, Accessibility},941};942this.checkScheme = checkScheme;...
FrameTree.js
Source:FrameTree.js
...59 }60 runtime() {61 return this._runtime;62 }63 setInitScripts(scripts) {64 for (const world of this._isolatedWorlds.values())65 world._scriptsToEvaluateOnNewDocument = [];66 for (let { worldName, script } of scripts) {67 worldName = worldName || '';68 const existing = this._isolatedWorlds.has(worldName);69 const world = this._ensureWorld(worldName);70 world._scriptsToEvaluateOnNewDocument.push(script);71 // FIXME: 'should inherit http credentials from browser context' fails without this72 if (worldName && !existing) {73 for (const frame of this.frames())74 frame._createIsolatedContext(worldName);75 }76 }77 }...
ffBrowser.js
Source:ffBrowser.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.FFBrowserContext = exports.FFBrowser = void 0;6var _errors = require("../../common/errors");7var _utils = require("../../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 doCreateNewContext(options) {73 if (options.isMobile) throw new Error('options.isMobile is not supported in Firefox');74 const {75 browserContextId76 } = await this._connection.send('Browser.createBrowserContext', {77 removeOnDetach: true78 });79 const context = new FFBrowserContext(this, browserContextId, options);80 await context._initialize();81 this._contexts.set(browserContextId, context);82 return context;83 }84 contexts() {85 return Array.from(this._contexts.values());86 }87 version() {88 return this._version;89 }90 userAgent() {91 return this._userAgent;92 }93 _onDetachedFromTarget(payload) {94 const ffPage = this._ffPages.get(payload.targetId);95 this._ffPages.delete(payload.targetId);96 ffPage.didClose();97 }98 _onAttachedToTarget(payload) {99 const {100 targetId,101 browserContextId,102 openerId,103 type104 } = payload.targetInfo;105 (0, _utils.assert)(type === 'page');106 const context = browserContextId ? this._contexts.get(browserContextId) : this._defaultContext;107 (0, _utils.assert)(context, `Unknown context id:${browserContextId}, _defaultContext: ${this._defaultContext}`);108 const session = this._connection.createSession(payload.sessionId);109 const opener = openerId ? this._ffPages.get(openerId) : null;110 const ffPage = new _ffPage.FFPage(session, context, opener);111 this._ffPages.set(targetId, ffPage);112 }113 _onDownloadCreated(payload) {114 const ffPage = this._ffPages.get(payload.pageTargetId);115 (0, _utils.assert)(ffPage);116 if (!ffPage) return;117 let originPage = ffPage._initializedPage; // If it's a new window download, report it on the opener page.118 if (!originPage) {119 // Resume the page creation with an error. The page will automatically close right120 // after the download begins.121 ffPage._markAsError(new Error('Starting new page download'));122 if (ffPage._opener) originPage = ffPage._opener._initializedPage;123 }124 if (!originPage) return;125 this._downloadCreated(originPage, payload.uuid, payload.url, payload.suggestedFileName);126 }127 _onDownloadFinished(payload) {128 const error = payload.canceled ? 'canceled' : payload.error;129 this._downloadFinished(payload.uuid, error);130 }131 _onVideoRecordingFinished(payload) {132 var _this$_takeVideo;133 (_this$_takeVideo = this._takeVideo(payload.screencastId)) === null || _this$_takeVideo === void 0 ? void 0 : _this$_takeVideo.reportFinished();134 }135 _onDisconnect() {136 for (const video of this._idToVideo.values()) video.artifact.reportFinished(_errors.kBrowserClosedError);137 this._idToVideo.clear();138 this._didClose();139 }140}141exports.FFBrowser = FFBrowser;142class FFBrowserContext extends _browserContext.BrowserContext {143 constructor(browser, browserContextId, options) {144 super(browser, options, browserContextId);145 }146 async _initialize() {147 (0, _utils.assert)(!this._ffPages().length);148 const browserContextId = this._browserContextId;149 const promises = [super._initialize()];150 promises.push(this._browser._connection.send('Browser.setDownloadOptions', {151 browserContextId,152 downloadOptions: {153 behavior: this._options.acceptDownloads ? 'saveToDisk' : 'cancel',154 downloadsDir: this._browser.options.downloadsPath155 }156 }));157 if (this._options.viewport) {158 const viewport = {159 viewportSize: {160 width: this._options.viewport.width,161 height: this._options.viewport.height162 },163 deviceScaleFactor: this._options.deviceScaleFactor || 1164 };165 promises.push(this._browser._connection.send('Browser.setDefaultViewport', {166 browserContextId,167 viewport168 }));169 }170 if (this._options.hasTouch) promises.push(this._browser._connection.send('Browser.setTouchOverride', {171 browserContextId,172 hasTouch: true173 }));174 if (this._options.userAgent) promises.push(this._browser._connection.send('Browser.setUserAgentOverride', {175 browserContextId,176 userAgent: this._options.userAgent177 }));178 if (this._options.bypassCSP) promises.push(this._browser._connection.send('Browser.setBypassCSP', {179 browserContextId,180 bypassCSP: true181 }));182 if (this._options.ignoreHTTPSErrors) promises.push(this._browser._connection.send('Browser.setIgnoreHTTPSErrors', {183 browserContextId,184 ignoreHTTPSErrors: true185 }));186 if (this._options.javaScriptEnabled === false) promises.push(this._browser._connection.send('Browser.setJavaScriptDisabled', {187 browserContextId,188 javaScriptDisabled: true189 }));190 if (this._options.locale) promises.push(this._browser._connection.send('Browser.setLocaleOverride', {191 browserContextId,192 locale: this._options.locale193 }));194 if (this._options.timezoneId) promises.push(this._browser._connection.send('Browser.setTimezoneOverride', {195 browserContextId,196 timezoneId: this._options.timezoneId197 }));198 if (this._options.permissions) promises.push(this.grantPermissions(this._options.permissions));199 if (this._options.extraHTTPHeaders || this._options.locale) promises.push(this.setExtraHTTPHeaders(this._options.extraHTTPHeaders || []));200 if (this._options.httpCredentials) promises.push(this.setHTTPCredentials(this._options.httpCredentials));201 if (this._options.geolocation) promises.push(this.setGeolocation(this._options.geolocation));202 if (this._options.offline) promises.push(this.setOffline(this._options.offline));203 promises.push(this._browser._connection.send('Browser.setColorScheme', {204 browserContextId,205 colorScheme: this._options.colorScheme !== undefined ? this._options.colorScheme : 'light'206 }));207 promises.push(this._browser._connection.send('Browser.setReducedMotion', {208 browserContextId,209 reducedMotion: this._options.reducedMotion !== undefined ? this._options.reducedMotion : 'no-preference'210 }));211 promises.push(this._browser._connection.send('Browser.setForcedColors', {212 browserContextId,213 forcedColors: this._options.forcedColors !== undefined ? this._options.forcedColors : 'none'214 }));215 if (this._options.recordVideo) {216 promises.push(this._ensureVideosPath().then(() => {217 return this._browser._connection.send('Browser.setVideoRecordingOptions', {218 // validateBrowserContextOptions ensures correct video size.219 options: { ...this._options.recordVideo.size,220 dir: this._options.recordVideo.dir221 },222 browserContextId: this._browserContextId223 });224 }));225 }226 if (this._options.proxy) {227 promises.push(this._browser._connection.send('Browser.setContextProxy', {228 browserContextId: this._browserContextId,229 ...toJugglerProxyOptions(this._options.proxy)230 }));231 }232 await Promise.all(promises);233 }234 _ffPages() {235 return Array.from(this._browser._ffPages.values()).filter(ffPage => ffPage._browserContext === this);236 }237 pages() {238 return this._ffPages().map(ffPage => ffPage._initializedPage).filter(pageOrNull => !!pageOrNull);239 }240 async newPageDelegate() {241 (0, _browserContext.assertBrowserContextIsNotOwned)(this);242 const {243 targetId244 } = await this._browser._connection.send('Browser.newPage', {245 browserContextId: this._browserContextId246 }).catch(e => {247 if (e.message.includes('Failed to override timezone')) throw new Error(`Invalid timezone ID: ${this._options.timezoneId}`);248 throw e;249 });250 return this._browser._ffPages.get(targetId);251 }252 async doGetCookies(urls) {253 const {254 cookies255 } = await this._browser._connection.send('Browser.getCookies', {256 browserContextId: this._browserContextId257 });258 return network.filterCookies(cookies.map(c => {259 const copy = { ...c260 };261 delete copy.size;262 delete copy.session;263 return copy;264 }), urls);265 }266 async addCookies(cookies) {267 const cc = network.rewriteCookies(cookies).map(c => ({ ...c,268 expires: c.expires && c.expires !== -1 ? c.expires : undefined269 }));270 await this._browser._connection.send('Browser.setCookies', {271 browserContextId: this._browserContextId,272 cookies: cc273 });274 }275 async clearCookies() {276 await this._browser._connection.send('Browser.clearCookies', {277 browserContextId: this._browserContextId278 });279 }280 async doGrantPermissions(origin, permissions) {281 const webPermissionToProtocol = new Map([['geolocation', 'geo'], ['persistent-storage', 'persistent-storage'], ['push', 'push'], ['notifications', 'desktop-notification']]);282 const filtered = permissions.map(permission => {283 const protocolPermission = webPermissionToProtocol.get(permission);284 if (!protocolPermission) throw new Error('Unknown permission: ' + permission);285 return protocolPermission;286 });287 await this._browser._connection.send('Browser.grantPermissions', {288 origin: origin,289 browserContextId: this._browserContextId,290 permissions: filtered291 });292 }293 async doClearPermissions() {294 await this._browser._connection.send('Browser.resetPermissions', {295 browserContextId: this._browserContextId296 });297 }298 async setGeolocation(geolocation) {299 (0, _browserContext.verifyGeolocation)(geolocation);300 this._options.geolocation = geolocation;301 await this._browser._connection.send('Browser.setGeolocationOverride', {302 browserContextId: this._browserContextId,303 geolocation: geolocation || null304 });305 }306 async setExtraHTTPHeaders(headers) {307 this._options.extraHTTPHeaders = headers;308 let allHeaders = this._options.extraHTTPHeaders;309 if (this._options.locale) allHeaders = network.mergeHeaders([allHeaders, network.singleHeader('Accept-Language', this._options.locale)]);310 await this._browser._connection.send('Browser.setExtraHTTPHeaders', {311 browserContextId: this._browserContextId,312 headers: allHeaders313 });314 }315 async setOffline(offline) {316 this._options.offline = offline;317 await this._browser._connection.send('Browser.setOnlineOverride', {318 browserContextId: this._browserContextId,319 override: offline ? 'offline' : 'online'320 });321 }322 async doSetHTTPCredentials(httpCredentials) {323 this._options.httpCredentials = httpCredentials;324 await this._browser._connection.send('Browser.setHTTPCredentials', {325 browserContextId: this._browserContextId,326 credentials: httpCredentials || null327 });328 }329 async doAddInitScript(source) {330 await this._browser._connection.send('Browser.setInitScripts', {331 browserContextId: this._browserContextId,332 scripts: this.initScripts.map(script => ({333 script334 }))335 });336 }337 async doRemoveInitScripts() {338 await this._browser._connection.send('Browser.setInitScripts', {339 browserContextId: this._browserContextId,340 scripts: []341 });342 }343 async doExposeBinding(binding) {344 await this._browser._connection.send('Browser.addBinding', {345 browserContextId: this._browserContextId,346 name: binding.name,347 script: binding.source348 });349 }350 async doRemoveExposedBindings() {// TODO: implement me.351 }352 async doUpdateRequestInterception() {353 await this._browser._connection.send('Browser.setRequestInterception', {354 browserContextId: this._browserContextId,355 enabled: !!this._requestInterceptor356 });357 }358 onClosePersistent() {}359 async doClose() {360 (0, _utils.assert)(this._browserContextId);361 await this._browser._connection.send('Browser.removeBrowserContext', {362 browserContextId: this._browserContextId363 });364 this._browser._contexts.delete(this._browserContextId);365 }366 async cancelDownload(uuid) {367 await this._browser._connection.send('Browser.cancelDownload', {368 uuid369 });370 }371}372exports.FFBrowserContext = FFBrowserContext;373function toJugglerProxyOptions(proxy) {374 const proxyServer = new URL(proxy.server);375 let port = parseInt(proxyServer.port, 10);376 let type = 'http';377 if (proxyServer.protocol === 'socks5:') type = 'socks';else if (proxyServer.protocol === 'socks4:') type = 'socks4';else if (proxyServer.protocol === 'https:') type = 'https';378 if (proxyServer.port === '') {379 if (proxyServer.protocol === 'http:') port = 80;else if (proxyServer.protocol === 'https:') port = 443;380 }381 return {382 type,383 bypass: proxy.bypass ? proxy.bypass.split(',').map(domain => domain.trim()) : [],384 host: proxyServer.hostname,385 port,386 username: proxy.username,387 password: proxy.password388 };...
PageHandler.js
Source:PageHandler.js
...279 async ['Page.scrollIntoViewIfNeeded'](options) {280 return await this._contentPage.send('scrollIntoViewIfNeeded', options);281 }282 async ['Page.setInitScripts']({ scripts }) {283 return await this._pageTarget.setInitScripts(scripts);284 }285 async ['Page.dispatchKeyEvent'](options) {286 return await this._contentPage.send('dispatchKeyEvent', options);287 }288 async ['Page.dispatchTouchEvent'](options) {289 return await this._contentPage.send('dispatchTouchEvent', options);290 }291 async ['Page.dispatchTapEvent'](options) {292 return await this._contentPage.send('dispatchTapEvent', options);293 }294 async ['Page.dispatchMouseEvent'](options) {295 return await this._contentPage.send('dispatchMouseEvent', options);296 }297 async ['Page.dispatchWheelEvent'](options) {...
BrowserHandler.js
Source:BrowserHandler.js
...209 async ['Browser.setScrollbarsHidden']({browserContextId, hidden}) {210 await this._targetRegistry.browserContextForId(browserContextId).applySetting('scrollbarsHidden', nullToUndefined(hidden));211 }212 async ['Browser.setInitScripts']({browserContextId, scripts}) {213 await this._targetRegistry.browserContextForId(browserContextId).setInitScripts(scripts);214 }215 async ['Browser.addBinding']({browserContextId, worldName, name, script}) {216 await this._targetRegistry.browserContextForId(browserContextId).addBinding(worldName, name, script);217 }218 ['Browser.setCookies']({browserContextId, cookies}) {219 this._targetRegistry.browserContextForId(browserContextId).setCookies(cookies);220 }221 ['Browser.clearCookies']({browserContextId}) {222 this._targetRegistry.browserContextForId(browserContextId).clearCookies();223 }224 ['Browser.getCookies']({browserContextId}) {225 const cookies = this._targetRegistry.browserContextForId(browserContextId).getCookies();226 return {cookies};227 }...
main.js
Source:main.js
...82 applySetting[name](value);83 }84 for (const { worldName, name, script } of bindings)85 frameTree.addBinding(worldName, name, script);86 frameTree.setInitScripts(initScripts);87 pageAgent = new PageAgent(messageManager, channel, frameTree);88 channel.register('', {89 setInitScripts(scripts) {90 frameTree.setInitScripts(scripts);91 },92 addBinding({worldName, name, script}) {93 frameTree.addBinding(worldName, name, script);94 },95 applyContextSetting({name, value}) {96 applySetting[name](value);97 },98 ensurePermissions() {99 // noop, just a rountrip.100 },101 hasFailedToOverrideTimezone() {102 return failedToOverrideTimezone;103 },104 async awaitViewportDimensions({width, height, deviceSizeIsPageSize}) {...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch({ headless: false });4 const context = await browser.newContext();5 await context.setInitScripts([{6 window.__test = 'test';7 }]);8 const page = await context.newPage();9 console.log(await page.evaluate(() => window.__test));10 await browser.close();11})();
Using AI Code Generation
1const playwright = require("playwright");2(async () => {3 const browser = await playwright.chromium.launch({ headless: false });4 const page = await browser.newPage();5 await browser.close();6})();7const playwright = require("playwright");8(async () => {9 const browser = await playwright.chromium.launch({ headless: false });10 const page = await browser.newPage();11 await browser.close();12})();13const playwright = require("playwright");14(async () => {15 const browser = await playwright.chromium.launch({ headless: false });16 const page = await browser.newPage();17 await browser.close();18})();19const playwright = require("playwright");20(async () => {21 const browser = await playwright.chromium.launch({ headless: false });22 const page = await browser.newPage();23 await browser.close();24})();25const playwright = require("playwright");26(async () => {27 const browser = await playwright.chromium.launch({ headless: false });28 const page = await browser.newPage();29 await browser.close();30})();31const playwright = require("playwright");32(async () => {33 const browser = await playwright.chromium.launch({ headless: false });34 const page = await browser.newPage();35 await browser.close();36})();37const playwright = require("playwright");38(async () => {39 const browser = await playwright.chromium.launch({ headless: false });40 const page = await browser.newPage();41 await browser.close();42})();43const playwright = require("playwright");44(async () => {45 const browser = await playwright.chromium.launch({ headless: false });
Using AI Code Generation
1const playwright = require('playwright');2const fs = require('fs');3(async () => {4 const browser = await playwright.chromium.launch({5 });6 const context = await browser.newContext();7 await context.setInitScripts([8 {9 source: fs.readFileSync('init.js', 'utf8'),10 },11 ]);12 const page = await context.newPage();13 await page.screenshot({ path: 'example.png' });14 await browser.close();15})();16window.init = () => {17 window.initValue = 'setInitScripts';18};19init();20const playwright = require('playwright');21const fs = require('fs');22(async () => {23 const browser = await playwright.chromium.launch({24 });25 const context = await browser.newContext({26 extraHTTPHeaders: {27 },28 });29 const page = await context.newPage();30 await page.screenshot({ path: 'example.png' });31 await browser.close();32})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch({4 '--disable-extensions-except=' + path.join(__dirname, 'extension'),5 '--load-extension=' + path.join(__dirname, 'extension'),6 });7 const context = await browser.newContext({8 });9 const page = await context.newPage();10 await page.setInitScripts([11 {12 path: path.join(__dirname, 'init.js'),13 },14 ]);15 await page.waitForNavigation();16 await page.screenshot({ path: 'example.png' });17 await browser.close();18})();19window.onload = function () {20 navigator.geolocation.getCurrentPosition = function (success, error, options) {21 success({22 coords: {23 },24 timestamp: new Date().getTime(),25 });26 };27};28{29 "background": {30 }31}32chrome.runtime.onInstalled.addListener(function () {33 chrome.permissions.request(34 {35 },36 function (granted) {37 if (granted) {38 console.log('Permission granted');39 } else {40 console.log('Permission not granted');41 }42 }43 );44});45{46 "background": {47 }48}
Using AI Code Generation
1const { setInitScripts } = require('playwright/lib/server/browserType');2setInitScripts({3 'console.log("Hello from Chromium")'4 'console.log("Hello from Firefox")'5 'console.log("Hello from WebKit")'6});7const { chromium } = require('playwright');8(async () => {9 const browser = await chromium.launch();10 const context = await browser.newContext();11 const page = await context.newPage();12 await browser.close();13})();14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 await browser.close();20})();21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch();24 const context = await browser.newContext();25 const page = await context.newPage();26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 await browser.close();34})();35const { chromium } = require('playwright');36(async () => {37 const browser = await chromium.launch();38 const context = await browser.newContext();39 const page = await context.newPage();40 await browser.close();41})();42const { chromium } = require('playwright');43(async () => {44 const browser = await chromium.launch();45 const context = await browser.newContext();46 const page = await context.newPage();47 await browser.close();48})();49const { chromium } = require('playwright');50(async () => {51 const browser = await chromium.launch();52 const context = await browser.newContext();53 const page = await context.newPage();
Using AI Code Generation
1const { setInitScripts } = require('playwright/lib/server/browserType');2setInitScripts([{3}]);4const { chromium } = require('playwright');5(async () => {6 const browser = await chromium.launch();7 const page = await browser.newPage();8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const page = await browser.newPage();14 await page.evaluate(() => {15 window.__injected = 123;16 });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const page = await browser.newPage();23 await page.evaluate(() => {24 const script = document.createElement('script');25 script.textContent = 'window.__injected = 123';26 document.body.appendChild(script);27 });28 await browser.close();29})();
Using AI Code Generation
1const { setInitScripts } = require('playwright-core/lib/server/initScript');2setInitScripts([3 {4 content: `console.log('test')`,5 },6]);7const { setInitScript } = require('playwright-core/lib/server/initScript');8setInitScript(`console.log('test')`);9const { setInitScripts } = require('playwright-core/lib/server/initScript');10setInitScripts([11 {12 content: `console.log('test')`,13 },14]);15const { setInitScript } = require('playwright-core/lib/server/initScript');16setInitScript(`console.log('test')`);17const { setInitScripts } = require('playwright-core/lib/server/initScript');18setInitScripts([19 {20 content: `console.log('test')`,21 },22]);23const { setInitScript } = require('playwright-core/lib/server/initScript');24setInitScript(`console.log('test')`);25const { setInitScripts } = require('playwright-core/lib/server/initScript');26setInitScripts([27 {28 content: `console.log('test')`,29 },30]);31const { setInitScript } = require('playwright-core/lib/server/initScript');32setInitScript(`console.log('test')`);33const { setInitScripts } = require('playwright-core/lib/server/initScript');34setInitScripts([35 {36 content: `console.log('test')`,37 },38]);39const { setInitScript } = require('playwright-core/lib/server/initScript');40setInitScript(`console.log('test')`);
Using AI Code Generation
1const { setInitScripts } = require('playwright/lib/server/initScripts');2setInitScripts([3 {4 source: `window.test = 'test value';`,5 },6]);7const { chromium } = require('playwright');8(async () => {9 const browser = await chromium.launch();10 const context = await browser.newContext();11 const page = await context.newPage();12 await page.evaluate(() => console.log(window.test));13 await browser.close();14})();15How to use the setInitScripts method with BrowserType.connect()16const { chromium } = require('playwright');17(async () => {18 const browserServer = await chromium.launchServer();19 const wsEndpoint = browserServer.wsEndpoint();20 const browser = await chromium.connect({ wsEndpoint });21 const context = await browser.newContext();22 const page = await context.newPage();23 await page.evaluate(() => console.log(window.test));24 await browser.close();25})();26How to use the setInitScripts method with BrowserType.launchPersistentContext()27const { chromium } = require('playwright');28(async () => {29 const browser = await chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();32 await page.evaluate(() => console.log(window.test));33 await browser.close();34})();35How to use the setInitScripts method with BrowserType.launchServer()36const { chromium } = require('playwright');
Using AI Code Generation
1const playwright = require('playwright');2const { setInitScripts } = require('playwright/lib/server/supplements/recorder/recorderSupplement');3const path = require('path');4(async () => {5 const browser = await playwright['chromium'].launch({6 });7 const context = await browser.newContext();8 const page = await context.newPage();9 const initScriptPath = path.join(__dirname, 'initScript.js');10 setInitScripts(page, [initScriptPath]);11 await page.screenshot({ path: 'example.png' });12 await browser.close();13})();14function initScript() {15 window.__initScript = function() {16 document.body.innerHTML = '<p>init script executed</p>';17 };18 window.__initScript();19}20initScript();
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!!