How to use setFileChooserIntercepted method in Playwright Internal

Best JavaScript code snippet using playwright-internal

crPage.js

Source:crPage.js Github

copy

Full Screen

...187 }188 async updateRequestInterception() {189 await this._forAllFrameSessions(frame => frame._updateRequestInterception());190 }191 async setFileChooserIntercepted(enabled) {192 await this._forAllFrameSessions(frame => frame.setFileChooserIntercepted(enabled));193 }194 async reload() {195 await this._mainFrameSession._client.send('Page.reload');196 }197 async _go(delta) {198 const history = await this._mainFrameSession._client.send('Page.getNavigationHistory');199 const entry = history.entries[history.currentIndex + delta];200 if (!entry) return false;201 await this._mainFrameSession._client.send('Page.navigateToHistoryEntry', {202 entryId: entry.id203 });204 return true;205 }206 goBack() {207 return this._go(-1);208 }209 goForward() {210 return this._go(+1);211 }212 async addInitScript(source, world = 'main') {213 await this._forAllFrameSessions(frame => frame._evaluateOnNewDocument(source, world));214 }215 async removeInitScripts() {216 await this._forAllFrameSessions(frame => frame._removeEvaluatesOnNewDocument());217 }218 async closePage(runBeforeUnload) {219 if (runBeforeUnload) await this._mainFrameSession._client.send('Page.close');else await this._browserContext._browser._closePage(this);220 }221 async setBackgroundColor(color) {222 await this._mainFrameSession._client.send('Emulation.setDefaultBackgroundColorOverride', {223 color224 });225 }226 async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport, scale) {227 const {228 visualViewport229 } = await this._mainFrameSession._client.send('Page.getLayoutMetrics');230 if (!documentRect) {231 documentRect = {232 x: visualViewport.pageX + viewportRect.x,233 y: visualViewport.pageY + viewportRect.y,234 ..._helper.helper.enclosingIntSize({235 width: viewportRect.width / visualViewport.scale,236 height: viewportRect.height / visualViewport.scale237 })238 };239 } // When taking screenshots with documentRect (based on the page content, not viewport),240 // ignore current page scale.241 const clip = { ...documentRect,242 scale: viewportRect ? visualViewport.scale : 1243 };244 if (scale === 'css') {245 const deviceScaleFactor = this._browserContext._options.deviceScaleFactor || 1;246 clip.scale /= deviceScaleFactor;247 }248 progress.throwIfAborted();249 const result = await this._mainFrameSession._client.send('Page.captureScreenshot', {250 format,251 quality,252 clip,253 captureBeyondViewport: !fitsViewport254 });255 return Buffer.from(result.data, 'base64');256 }257 async getContentFrame(handle) {258 return this._sessionForHandle(handle)._getContentFrame(handle);259 }260 async getOwnerFrame(handle) {261 return this._sessionForHandle(handle)._getOwnerFrame(handle);262 }263 isElementHandle(remoteObject) {264 return remoteObject.subtype === 'node';265 }266 async getBoundingBox(handle) {267 return this._sessionForHandle(handle)._getBoundingBox(handle);268 }269 async scrollRectIntoViewIfNeeded(handle, rect) {270 return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);271 }272 async setScreencastOptions(options) {273 if (options) {274 await this._mainFrameSession._startScreencast(this, {275 format: 'jpeg',276 quality: options.quality,277 maxWidth: options.width,278 maxHeight: options.height279 });280 } else {281 await this._mainFrameSession._stopScreencast(this);282 }283 }284 rafCountForStablePosition() {285 return 1;286 }287 async getContentQuads(handle) {288 return this._sessionForHandle(handle)._getContentQuads(handle);289 }290 async setInputFiles(handle, files) {291 await handle.evaluateInUtility(([injected, node, files]) => injected.setInputFiles(node, files), files);292 }293 async setInputFilePaths(handle, files) {294 const frame = await handle.ownerFrame();295 if (!frame) throw new Error('Cannot set input files to detached input element');296 const parentSession = this._sessionForFrame(frame);297 await parentSession._client.send('DOM.setFileInputFiles', {298 objectId: handle._objectId,299 files300 });301 }302 async adoptElementHandle(handle, to) {303 return this._sessionForHandle(handle)._adoptElementHandle(handle, to);304 }305 async getAccessibilityTree(needle) {306 return (0, _crAccessibility.getAccessibilityTree)(this._mainFrameSession._client, needle);307 }308 async inputActionEpilogue() {309 await this._mainFrameSession._client.send('Page.enable').catch(e => {});310 }311 async pdf(options) {312 return this._pdf.generate(options);313 }314 coverage() {315 return this._coverage;316 }317 async getFrameElement(frame) {318 let parent = frame.parentFrame();319 if (!parent) throw new Error('Frame has been detached.');320 const parentSession = this._sessionForFrame(parent);321 const {322 backendNodeId323 } = await parentSession._client.send('DOM.getFrameOwner', {324 frameId: frame._id325 }).catch(e => {326 if (e instanceof Error && e.message.includes('Frame with the given id was not found.')) (0, _stackTrace.rewriteErrorMessage)(e, 'Frame has been detached.');327 throw e;328 });329 parent = frame.parentFrame();330 if (!parent) throw new Error('Frame has been detached.');331 return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());332 }333}334exports.CRPage = CRPage;335class FrameSession {336 // Marks the oopif session that remote -> local transition has happened in the parent.337 // See Target.detachedFromTarget handler for details.338 constructor(crPage, client, targetId, parentSession) {339 this._client = void 0;340 this._crPage = void 0;341 this._page = void 0;342 this._networkManager = void 0;343 this._contextIdToContext = new Map();344 this._eventListeners = [];345 this._targetId = void 0;346 this._firstNonInitialNavigationCommittedPromise = void 0;347 this._firstNonInitialNavigationCommittedFulfill = () => {};348 this._firstNonInitialNavigationCommittedReject = e => {};349 this._windowId = void 0;350 this._swappedIn = false;351 this._videoRecorder = null;352 this._screencastId = null;353 this._screencastClients = new Set();354 this._evaluateOnNewDocumentIdentifiers = [];355 this._exposedBindingNames = [];356 this._client = client;357 this._crPage = crPage;358 this._page = crPage._page;359 this._targetId = targetId;360 this._networkManager = new _crNetworkManager.CRNetworkManager(client, this._page, parentSession ? parentSession._networkManager : null);361 this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {362 this._firstNonInitialNavigationCommittedFulfill = f;363 this._firstNonInitialNavigationCommittedReject = r;364 });365 client.once(_crConnection.CRSessionEvents.Disconnected, () => {366 this._firstNonInitialNavigationCommittedReject(new Error('Page closed'));367 });368 }369 _isMainFrame() {370 return this._targetId === this._crPage._targetId;371 }372 _addRendererListeners() {373 this._eventListeners.push(...[_eventsHelper.eventsHelper.addEventListener(this._client, 'Log.entryAdded', event => this._onLogEntryAdded(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.fileChooserOpened', event => this._onFileChooserOpened(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameDetached', event => this._onFrameDetached(event.frameId, event.reason)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame, false)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameRequestedNavigation', event => this._onFrameRequestedNavigation(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.javascriptDialogOpening', event => this._onDialog(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.bindingCalled', event => this._onBindingCalled(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.consoleAPICalled', event => this._onConsoleAPI(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.exceptionThrown', exception => this._handleException(exception.exceptionDetails)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.executionContextDestroyed', event => this._onExecutionContextDestroyed(event.executionContextId)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.executionContextsCleared', event => this._onExecutionContextsCleared()), _eventsHelper.eventsHelper.addEventListener(this._client, 'Target.attachedToTarget', event => this._onAttachedToTarget(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Target.detachedFromTarget', event => this._onDetachedFromTarget(event))]);374 }375 _addBrowserListeners() {376 this._eventListeners.push(...[_eventsHelper.eventsHelper.addEventListener(this._client, 'Inspector.targetCrashed', event => this._onTargetCrashed()), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.screencastFrame', event => this._onScreencastFrame(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.windowOpen', event => this._onWindowOpen(event))]);377 }378 async _initialize(hasUIWindow) {379 const isSettingStorageState = this._page._browserContext.isSettingStorageState();380 if (!isSettingStorageState && hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) {381 const {382 windowId383 } = await this._client.send('Browser.getWindowForTarget');384 this._windowId = windowId;385 }386 let screencastOptions;387 if (!isSettingStorageState && this._isMainFrame() && this._crPage._browserContext._options.recordVideo && hasUIWindow) {388 const screencastId = (0, _utils.createGuid)();389 const outputFile = _path.default.join(this._crPage._browserContext._options.recordVideo.dir, screencastId + '.webm');390 screencastOptions = { // validateBrowserContextOptions ensures correct video size.391 ...this._crPage._browserContext._options.recordVideo.size,392 outputFile393 };394 await this._crPage._browserContext._ensureVideosPath(); // Note: it is important to start video recorder before sending Page.startScreencast,395 // and it is equally important to send Page.startScreencast before sending Runtime.runIfWaitingForDebugger.396 await this._createVideoRecorder(screencastId, screencastOptions);397 this._crPage.pageOrError().then(p => {398 if (p instanceof Error) this._stopVideoRecording().catch(() => {});399 });400 }401 let lifecycleEventsEnabled;402 if (!this._isMainFrame()) this._addRendererListeners();403 this._addBrowserListeners();404 const promises = [this._client.send('Page.enable'), this._client.send('Page.getFrameTree').then(({405 frameTree406 }) => {407 if (this._isMainFrame()) {408 this._handleFrameTree(frameTree);409 this._addRendererListeners();410 }411 const localFrames = this._isMainFrame() ? this._page.frames() : [this._page._frameManager.frame(this._targetId)];412 for (const frame of localFrames) {413 // Note: frames might be removed before we send these.414 this._client._sendMayFail('Page.createIsolatedWorld', {415 frameId: frame._id,416 grantUniveralAccess: true,417 worldName: UTILITY_WORLD_NAME418 });419 for (const binding of this._crPage._browserContext._pageBindings.values()) frame.evaluateExpression(binding.source, false, undefined).catch(e => {});420 for (const source of this._crPage._browserContext.initScripts) frame.evaluateExpression(source, false, undefined, 'main').catch(e => {});421 }422 const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ':';423 if (isInitialEmptyPage) {424 // Ignore lifecycle events for the initial empty page. It is never the final page425 // hence we are going to get more lifecycle updates after the actual navigation has426 // started (even if the target url is about:blank).427 lifecycleEventsEnabled.catch(e => {}).then(() => {428 this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));429 });430 } else {431 this._firstNonInitialNavigationCommittedFulfill();432 this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));433 }434 }), this._client.send('Log.enable', {}), lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', {435 enabled: true436 }), this._client.send('Runtime.enable', {}), this._client.send('Page.addScriptToEvaluateOnNewDocument', {437 source: '',438 worldName: UTILITY_WORLD_NAME439 }), this._networkManager.initialize(), this._client.send('Target.setAutoAttach', {440 autoAttach: true,441 waitForDebuggerOnStart: true,442 flatten: true443 })];444 if (!isSettingStorageState) {445 if (this._isMainFrame()) promises.push(this._client.send('Emulation.setFocusEmulationEnabled', {446 enabled: true447 }));448 const options = this._crPage._browserContext._options;449 if (options.bypassCSP) promises.push(this._client.send('Page.setBypassCSP', {450 enabled: true451 }));452 if (options.ignoreHTTPSErrors) promises.push(this._client.send('Security.setIgnoreCertificateErrors', {453 ignore: true454 }));455 if (this._isMainFrame()) promises.push(this._updateViewport());456 if (options.hasTouch) promises.push(this._client.send('Emulation.setTouchEmulationEnabled', {457 enabled: true458 }));459 if (options.javaScriptEnabled === false) promises.push(this._client.send('Emulation.setScriptExecutionDisabled', {460 value: true461 }));462 if (options.userAgent || options.locale) promises.push(this._client.send('Emulation.setUserAgentOverride', {463 userAgent: options.userAgent || '',464 acceptLanguage: options.locale465 }));466 if (options.locale) promises.push(emulateLocale(this._client, options.locale));467 if (options.timezoneId) promises.push(emulateTimezone(this._client, options.timezoneId));468 if (!this._crPage._browserContext._browser.options.headful) promises.push(this._setDefaultFontFamilies(this._client));469 promises.push(this._updateGeolocation(true));470 promises.push(this._updateExtraHTTPHeaders(true));471 promises.push(this._updateRequestInterception());472 promises.push(this._updateOffline(true));473 promises.push(this._updateHttpCredentials(true));474 promises.push(this._updateEmulateMedia(true));475 for (const binding of this._crPage._page.allBindings()) promises.push(this._initBinding(binding));476 for (const source of this._crPage._browserContext.initScripts) promises.push(this._evaluateOnNewDocument(source, 'main'));477 for (const source of this._crPage._page.initScripts) promises.push(this._evaluateOnNewDocument(source, 'main'));478 if (screencastOptions) promises.push(this._startVideoRecording(screencastOptions));479 }480 promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));481 promises.push(this._firstNonInitialNavigationCommittedPromise);482 await Promise.all(promises);483 }484 dispose() {485 _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);486 this._networkManager.dispose();487 this._crPage._sessions.delete(this._targetId);488 }489 async _navigate(frame, url, referrer) {490 const response = await this._client.send('Page.navigate', {491 url,492 referrer,493 frameId: frame._id494 });495 if (response.errorText) throw new Error(`${response.errorText} at ${url}`);496 return {497 newDocumentId: response.loaderId498 };499 }500 _onLifecycleEvent(event) {501 if (this._eventBelongsToStaleFrame(event.frameId)) return;502 if (event.name === 'load') this._page._frameManager.frameLifecycleEvent(event.frameId, 'load');else if (event.name === 'DOMContentLoaded') this._page._frameManager.frameLifecycleEvent(event.frameId, 'domcontentloaded');503 }504 _onFrameStoppedLoading(frameId) {505 if (this._eventBelongsToStaleFrame(frameId)) return;506 this._page._frameManager.frameStoppedLoading(frameId);507 }508 _handleFrameTree(frameTree) {509 this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);510 this._onFrameNavigated(frameTree.frame, true);511 if (!frameTree.childFrames) return;512 for (const child of frameTree.childFrames) this._handleFrameTree(child);513 }514 _eventBelongsToStaleFrame(frameId) {515 const frame = this._page._frameManager.frame(frameId); // Subtree may be already gone because some ancestor navigation destroyed the oopif.516 if (!frame) return true; // When frame goes remote, parent process may still send some events517 // related to the local frame before it sends frameDetached.518 // In this case, we already have a new session for this frame, so events519 // in the old session should be ignored.520 const session = this._crPage._sessionForFrame(frame);521 return session && session !== this && !session._swappedIn;522 }523 _onFrameAttached(frameId, parentFrameId) {524 const frameSession = this._crPage._sessions.get(frameId);525 if (frameSession && frameId !== this._targetId) {526 // This is a remote -> local frame transition.527 frameSession._swappedIn = true;528 const frame = this._page._frameManager.frame(frameId); // Frame or even a whole subtree may be already gone, because some ancestor did navigate.529 if (frame) this._page._frameManager.removeChildFramesRecursively(frame);530 return;531 }532 if (parentFrameId && !this._page._frameManager.frame(parentFrameId)) {533 // Parent frame may be gone already because some ancestor frame navigated and534 // destroyed the whole subtree of some oopif, while oopif's process is still sending us events.535 // Be careful to not confuse this with "main frame navigated cross-process" scenario536 // where parentFrameId is null.537 return;538 }539 this._page._frameManager.frameAttached(frameId, parentFrameId);540 }541 _onFrameNavigated(framePayload, initial) {542 if (this._eventBelongsToStaleFrame(framePayload.id)) return;543 this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ''), framePayload.name || '', framePayload.loaderId, initial);544 if (!initial) this._firstNonInitialNavigationCommittedFulfill();545 }546 _onFrameRequestedNavigation(payload) {547 if (this._eventBelongsToStaleFrame(payload.frameId)) return;548 if (payload.disposition === 'currentTab') this._page._frameManager.frameRequestedNavigation(payload.frameId);549 }550 _onFrameNavigatedWithinDocument(frameId, url) {551 if (this._eventBelongsToStaleFrame(frameId)) return;552 this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);553 }554 _onFrameDetached(frameId, reason) {555 if (this._crPage._sessions.has(frameId)) {556 // This is a local -> remote frame transtion, where557 // Page.frameDetached arrives after Target.attachedToTarget.558 // We've already handled the new target and frame reattach - nothing to do here.559 return;560 }561 if (reason === 'swap') {562 // This is a local -> remote frame transtion, where563 // Page.frameDetached arrives before Target.attachedToTarget.564 // We should keep the frame in the tree, and it will be used for the new target.565 const frame = this._page._frameManager.frame(frameId);566 if (frame) this._page._frameManager.removeChildFramesRecursively(frame);567 return;568 } // Just a regular frame detach.569 this._page._frameManager.frameDetached(frameId);570 }571 _onExecutionContextCreated(contextPayload) {572 const frame = contextPayload.auxData ? this._page._frameManager.frame(contextPayload.auxData.frameId) : null;573 if (!frame || this._eventBelongsToStaleFrame(frame._id)) return;574 const delegate = new _crExecutionContext.CRExecutionContext(this._client, contextPayload);575 let worldName = null;576 if (contextPayload.auxData && !!contextPayload.auxData.isDefault) worldName = 'main';else if (contextPayload.name === UTILITY_WORLD_NAME) worldName = 'utility';577 const context = new dom.FrameExecutionContext(delegate, frame, worldName);578 context[contextDelegateSymbol] = delegate;579 if (worldName) frame._contextCreated(worldName, context);580 this._contextIdToContext.set(contextPayload.id, context);581 }582 _onExecutionContextDestroyed(executionContextId) {583 const context = this._contextIdToContext.get(executionContextId);584 if (!context) return;585 this._contextIdToContext.delete(executionContextId);586 context.frame._contextDestroyed(context);587 }588 _onExecutionContextsCleared() {589 for (const contextId of Array.from(this._contextIdToContext.keys())) this._onExecutionContextDestroyed(contextId);590 }591 _onAttachedToTarget(event) {592 const session = _crConnection.CRConnection.fromSession(this._client).session(event.sessionId);593 if (event.targetInfo.type === 'iframe') {594 // Frame id equals target id.595 const targetId = event.targetInfo.targetId;596 const frame = this._page._frameManager.frame(targetId);597 if (!frame) return; // Subtree may be already gone due to renderer/browser race.598 this._page._frameManager.removeChildFramesRecursively(frame);599 const frameSession = new FrameSession(this._crPage, session, targetId, this);600 this._crPage._sessions.set(targetId, frameSession);601 frameSession._initialize(false).catch(e => e);602 return;603 }604 if (event.targetInfo.type !== 'worker') {605 // Ideally, detaching should resume any target, but there is a bug in the backend.606 session._sendMayFail('Runtime.runIfWaitingForDebugger').then(() => {607 this._client._sendMayFail('Target.detachFromTarget', {608 sessionId: event.sessionId609 });610 });611 return;612 }613 const url = event.targetInfo.url;614 const worker = new _page.Worker(this._page, url);615 this._page._addWorker(event.sessionId, worker);616 session.once('Runtime.executionContextCreated', async event => {617 worker._createExecutionContext(new _crExecutionContext.CRExecutionContext(session, event.context));618 }); // This might fail if the target is closed before we initialize.619 session._sendMayFail('Runtime.enable');620 session._sendMayFail('Network.enable');621 session._sendMayFail('Runtime.runIfWaitingForDebugger');622 session.on('Runtime.consoleAPICalled', event => {623 const args = event.args.map(o => worker._existingExecutionContext.createHandle(o));624 this._page._addConsoleMessage(event.type, args, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));625 });626 session.on('Runtime.exceptionThrown', exception => this._page.emit(_page.Page.Events.PageError, (0, _crProtocolHelper.exceptionToError)(exception.exceptionDetails))); // TODO: attribute workers to the right frame.627 this._networkManager.instrumentNetworkEvents(session, this._page._frameManager.frame(this._targetId));628 }629 _onDetachedFromTarget(event) {630 // This might be a worker...631 this._page._removeWorker(event.sessionId); // ... or an oopif.632 const childFrameSession = this._crPage._sessions.get(event.targetId);633 if (!childFrameSession) return; // Usually, we get frameAttached in this session first and mark child as swappedIn.634 if (childFrameSession._swappedIn) {635 childFrameSession.dispose();636 return;637 } // However, sometimes we get detachedFromTarget before frameAttached.638 // In this case we don't know wheter this is a remote frame detach,639 // or just a remote -> local transition. In the latter case, frameAttached640 // is already inflight, so let's make a safe roundtrip to ensure it arrives.641 this._client.send('Page.enable').catch(e => null).then(() => {642 // Child was not swapped in - that means frameAttached did not happen and643 // this is remote detach rather than remote -> local swap.644 if (!childFrameSession._swappedIn) this._page._frameManager.frameDetached(event.targetId);645 childFrameSession.dispose();646 });647 }648 _onWindowOpen(event) {649 this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);650 }651 async _onConsoleAPI(event) {652 if (event.executionContextId === 0) {653 // DevTools protocol stores the last 1000 console messages. These654 // messages are always reported even for removed execution contexts. In655 // this case, they are marked with executionContextId = 0 and are656 // reported upon enabling Runtime agent.657 //658 // Ignore these messages since:659 // - there's no execution context we can use to operate with message660 // arguments661 // - these messages are reported before Playwright clients can subscribe662 // to the 'console'663 // page event.664 //665 // @see https://github.com/GoogleChrome/puppeteer/issues/3865666 return;667 }668 const context = this._contextIdToContext.get(event.executionContextId);669 if (!context) return;670 const values = event.args.map(arg => context.createHandle(arg));671 this._page._addConsoleMessage(event.type, values, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));672 }673 async _initBinding(binding) {674 const [, response] = await Promise.all([this._client.send('Runtime.addBinding', {675 name: binding.name676 }), this._client.send('Page.addScriptToEvaluateOnNewDocument', {677 source: binding.source678 })]);679 this._exposedBindingNames.push(binding.name);680 this._evaluateOnNewDocumentIdentifiers.push(response.identifier);681 }682 async _removeExposedBindings() {683 const names = this._exposedBindingNames;684 this._exposedBindingNames = [];685 await Promise.all(names.map(name => this._client.send('Runtime.removeBinding', {686 name687 })));688 }689 async _onBindingCalled(event) {690 const pageOrError = await this._crPage.pageOrError();691 if (!(pageOrError instanceof Error)) {692 const context = this._contextIdToContext.get(event.executionContextId);693 if (context) await this._page._onBindingCalled(event.payload, context);694 }695 }696 _onDialog(event) {697 if (!this._page._frameManager.frame(this._targetId)) return; // Our frame/subtree may be gone already.698 this._page.emit(_page.Page.Events.Dialog, new dialog.Dialog(this._page, event.type, event.message, async (accept, promptText) => {699 await this._client.send('Page.handleJavaScriptDialog', {700 accept,701 promptText702 });703 }, event.defaultPrompt));704 }705 _handleException(exceptionDetails) {706 this._page.firePageError((0, _crProtocolHelper.exceptionToError)(exceptionDetails));707 }708 async _onTargetCrashed() {709 this._client._markAsCrashed();710 this._page._didCrash();711 }712 _onLogEntryAdded(event) {713 const {714 level,715 text,716 args,717 source,718 url,719 lineNumber720 } = event.entry;721 if (args) args.map(arg => (0, _crProtocolHelper.releaseObject)(this._client, arg.objectId));722 if (source !== 'worker') {723 const location = {724 url: url || '',725 lineNumber: lineNumber || 0,726 columnNumber: 0727 };728 this._page._addConsoleMessage(level, [], location, text);729 }730 }731 async _onFileChooserOpened(event) {732 const frame = this._page._frameManager.frame(event.frameId);733 if (!frame) return;734 let handle;735 try {736 const utilityContext = await frame._utilityContext();737 handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);738 } catch (e) {739 // During async processing, frame/context may go away. We should not throw.740 return;741 }742 await this._page._onFileChooserOpened(handle);743 }744 _willBeginDownload() {745 const originPage = this._crPage._initializedPage;746 if (!originPage) {747 // Resume the page creation with an error. The page will automatically close right748 // after the download begins.749 this._firstNonInitialNavigationCommittedReject(new Error('Starting new page download'));750 }751 }752 _onScreencastFrame(payload) {753 this._page.throttleScreencastFrameAck(() => {754 this._client.send('Page.screencastFrameAck', {755 sessionId: payload.sessionId756 }).catch(() => {});757 });758 const buffer = Buffer.from(payload.data, 'base64');759 this._page.emit(_page.Page.Events.ScreencastFrame, {760 buffer,761 timestamp: payload.metadata.timestamp,762 width: payload.metadata.deviceWidth,763 height: payload.metadata.deviceHeight764 });765 }766 async _createVideoRecorder(screencastId, options) {767 (0, _utils.assert)(!this._screencastId);768 const ffmpegPath = _registry.registry.findExecutable('ffmpeg').executablePathOrDie(this._page._browserContext._browser.options.sdkLanguage);769 this._videoRecorder = await _videoRecorder.VideoRecorder.launch(this._crPage._page, ffmpegPath, options);770 this._screencastId = screencastId;771 }772 async _startVideoRecording(options) {773 const screencastId = this._screencastId;774 (0, _utils.assert)(screencastId);775 this._page.once(_page.Page.Events.Close, () => this._stopVideoRecording().catch(() => {}));776 const gotFirstFrame = new Promise(f => this._client.once('Page.screencastFrame', f));777 await this._startScreencast(this._videoRecorder, {778 format: 'jpeg',779 quality: 90,780 maxWidth: options.width,781 maxHeight: options.height782 }); // Wait for the first frame before reporting video to the client.783 gotFirstFrame.then(() => {784 this._crPage._browserContext._browser._videoStarted(this._crPage._browserContext, screencastId, options.outputFile, this._crPage.pageOrError());785 });786 }787 async _stopVideoRecording() {788 if (!this._screencastId) return;789 const screencastId = this._screencastId;790 this._screencastId = null;791 const recorder = this._videoRecorder;792 this._videoRecorder = null;793 await this._stopScreencast(recorder);794 await recorder.stop().catch(() => {}); // Keep the video artifact in the map utntil encoding is fully finished, if the context795 // starts closing before the video is fully written to disk it will wait for it.796 const video = this._crPage._browserContext._browser._takeVideo(screencastId);797 video === null || video === void 0 ? void 0 : video.reportFinished();798 }799 async _startScreencast(client, options = {}) {800 this._screencastClients.add(client);801 if (this._screencastClients.size === 1) await this._client.send('Page.startScreencast', options);802 }803 async _stopScreencast(client) {804 this._screencastClients.delete(client);805 if (!this._screencastClients.size) await this._client._sendMayFail('Page.stopScreencast');806 }807 async _updateExtraHTTPHeaders(initial) {808 const headers = network.mergeHeaders([this._crPage._browserContext._options.extraHTTPHeaders, this._page._state.extraHTTPHeaders]);809 if (!initial || headers.length) await this._client.send('Network.setExtraHTTPHeaders', {810 headers: (0, _utils.headersArrayToObject)(headers, false811 /* lowerCase */812 )813 });814 }815 async _updateGeolocation(initial) {816 const geolocation = this._crPage._browserContext._options.geolocation;817 if (!initial || geolocation) await this._client.send('Emulation.setGeolocationOverride', geolocation || {});818 }819 async _updateOffline(initial) {820 const offline = !!this._crPage._browserContext._options.offline;821 if (!initial || offline) await this._networkManager.setOffline(offline);822 }823 async _updateHttpCredentials(initial) {824 const credentials = this._crPage._browserContext._options.httpCredentials || null;825 if (!initial || credentials) await this._networkManager.authenticate(credentials);826 }827 async _updateViewport() {828 if (this._crPage._browserContext._browser.isClank()) return;829 (0, _utils.assert)(this._isMainFrame());830 const options = this._crPage._browserContext._options;831 const emulatedSize = this._page._state.emulatedSize;832 if (emulatedSize === null) return;833 const viewportSize = emulatedSize.viewport;834 const screenSize = emulatedSize.screen;835 const isLandscape = viewportSize.width > viewportSize.height;836 const promises = [this._client.send('Emulation.setDeviceMetricsOverride', {837 mobile: !!options.isMobile,838 width: viewportSize.width,839 height: viewportSize.height,840 screenWidth: screenSize.width,841 screenHeight: screenSize.height,842 deviceScaleFactor: options.deviceScaleFactor || 1,843 screenOrientation: isLandscape ? {844 angle: 90,845 type: 'landscapePrimary'846 } : {847 angle: 0,848 type: 'portraitPrimary'849 }850 })];851 if (this._windowId) {852 let insets = {853 width: 0,854 height: 0855 };856 if (this._crPage._browserContext._browser.options.headful) {857 // TODO: popup windows have their own insets.858 insets = {859 width: 24,860 height: 88861 };862 if (process.platform === 'win32') insets = {863 width: 16,864 height: 88865 };else if (process.platform === 'linux') insets = {866 width: 8,867 height: 85868 };else if (process.platform === 'darwin') insets = {869 width: 2,870 height: 80871 };872 if (this._crPage._browserContext.isPersistentContext()) {873 // FIXME: Chrome bug: OOPIF router is confused when hit target is874 // outside browser window.875 // Account for the infobar here to work around the bug.876 insets.height += 46;877 }878 }879 promises.push(this.setWindowBounds({880 width: viewportSize.width + insets.width,881 height: viewportSize.height + insets.height882 }));883 }884 await Promise.all(promises);885 }886 async windowBounds() {887 const {888 bounds889 } = await this._client.send('Browser.getWindowBounds', {890 windowId: this._windowId891 });892 return bounds;893 }894 async setWindowBounds(bounds) {895 return await this._client.send('Browser.setWindowBounds', {896 windowId: this._windowId,897 bounds898 });899 }900 async _updateEmulateMedia(initial) {901 const colorScheme = this._page._state.colorScheme === null ? '' : this._page._state.colorScheme;902 const reducedMotion = this._page._state.reducedMotion === null ? '' : this._page._state.reducedMotion;903 const forcedColors = this._page._state.forcedColors === null ? '' : this._page._state.forcedColors;904 const features = [{905 name: 'prefers-color-scheme',906 value: colorScheme907 }, {908 name: 'prefers-reduced-motion',909 value: reducedMotion910 }, {911 name: 'forced-colors',912 value: forcedColors913 }]; // Empty string disables the override.914 await this._client.send('Emulation.setEmulatedMedia', {915 media: this._page._state.mediaType || '',916 features917 });918 }919 async _setDefaultFontFamilies(session) {920 const fontFamilies = _defaultFontFamilies.platformToFontFamilies[this._crPage._browserContext._browser._platform()];921 await session.send('Page.setFontFamilies', fontFamilies);922 }923 async _updateRequestInterception() {924 await this._networkManager.setRequestInterception(this._page._needsRequestInterception());925 }926 async setFileChooserIntercepted(enabled) {927 await this._client.send('Page.setInterceptFileChooserDialog', {928 enabled929 }).catch(e => {}); // target can be closed.930 }931 async _evaluateOnNewDocument(source, world) {932 const worldName = world === 'utility' ? UTILITY_WORLD_NAME : undefined;933 const {934 identifier935 } = await this._client.send('Page.addScriptToEvaluateOnNewDocument', {936 source,937 worldName938 });939 this._evaluateOnNewDocumentIdentifiers.push(identifier);940 }...

Full Screen

Full Screen

page.js

Source:page.js Github

copy

Full Screen

...427 worker.didClose();428 this._workers.delete(workerId);429 }430 }431 async setFileChooserIntercepted(enabled) {432 await this._delegate.setFileChooserIntercepted(enabled);433 }434 frameNavigatedToNewDocument(frame) {435 this.emit(Page.Events.InternalFrameNavigatedToNewDocument, frame);436 const url = frame.url();437 if (!url.startsWith('http')) return;438 const purl = network.parsedURL(url);439 if (purl) this._browserContext.addVisitedOrigin(purl.origin);440 }441 allBindings() {442 return [...this._browserContext._pageBindings.values(), ...this._pageBindings.values()];443 }444 getBinding(name) {445 return this._pageBindings.get(name) || this._browserContext._pageBindings.get(name);446 }...

Full Screen

Full Screen

ffPage.js

Source:ffPage.js Github

copy

Full Screen

...332 }333 async updateRequestInterception() {334 await this._networkManager.setRequestInterception(this._page._needsRequestInterception());335 }336 async setFileChooserIntercepted(enabled) {337 await this._session.send('Page.setInterceptFileChooserDialog', {338 enabled339 }).catch(e => {}); // target can be closed.340 }341 async reload() {342 await this._session.send('Page.reload', {343 frameId: this._page.mainFrame()._id344 });345 }346 async goBack() {347 const {348 success349 } = await this._session.send('Page.goBack', {350 frameId: this._page.mainFrame()._id...

Full Screen

Full Screen

pageDispatcher.js

Source:pageDispatcher.js Github

copy

Full Screen

...206 async close(params, metadata) {207 await this._page.close(metadata, params);208 }209 async setFileChooserInterceptedNoReply(params, metadata) {210 await this._page.setFileChooserIntercepted(params.intercepted);211 }212 async keyboardDown(params, metadata) {213 await this._page.keyboard.down(params.key);214 }215 async keyboardUp(params, metadata) {216 await this._page.keyboard.up(params.key);217 }218 async keyboardInsertText(params, metadata) {219 await this._page.keyboard.insertText(params.text);220 }221 async keyboardType(params, metadata) {222 await this._page.keyboard.type(params.text, params);223 }224 async keyboardPress(params, metadata) {...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**/*', route => {7 route.continue();8 });9 await page.evaluate(() => {10 window['playwright'].setFileChooserIntercepted(true);11 });12 await page.click('#tryhome > div > div > div > div > div.col-12.col-md-9 > div:nth-child(1) > div > div > div > div > div > div > div > div > div > form > div:nth-child(1) > div > input[type=file]');13 await page.waitForTimeout(5000);14 await browser.close();15})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**/*', route => {7 route.fulfill({8 body: JSON.stringify({9 })10 });11 });12 await page.setContent(`<input type="file" name="test" />`);13 await page.setInputFiles('input[type="file"]', 'test.js');14 await page.evaluate(() => document.querySelector('input[type="file"]').files[0].name);15 await browser.close();16})();17Your name to display (optional):18Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**/*', route => route.continue());7 await page.setContent(`<input type="file" />`);8 await page.setInputFiles('input[type="file"]', 'test.js');9 await page.click('input[type="file"]');10 await page.evaluate(() => {11 window.setFileChooserIntercepted(true);12 });13 await page.route('**/*', route => route.continue());14 await page.setContent(`<input type="file" />`);15 await page.setInputFiles('input[type="file"]', 'test.js');16 await page.click('input[type="file"]');17 await page.evaluate(() => {18 window.setFileChooserIntercepted(false);19 });20 await page.route('**/*', route => route.continue());21 await page.setContent(`<input type="file" />`);22 await page.setInputFiles('input[type="file"]', 'test.js');23 await page.click('input[type="file"]');24 await browser.close();25})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 await context._setFileChooserIntercepted(true);6 const page = await context.newPage();7 page.on('filechooser', async (fileChooser) => {8 await fileChooser.setFiles('/Users/username/Desktop/abc.png');9 });10 await page.click('input#fileURL');11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch({ headless: false });15 const context = await browser.newContext();16 await context._setFileChooserIntercepted(true);17 const page = await context.newPage();18 page.on('filechooser', async (fileChooser) => {19 await fileChooser.setFiles('/Users/username/Desktop/abc.png');20 });21 await page.click('input#fileURL');22})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const [fileChooser] = await Promise.all([7 page.waitForEvent('filechooser'),8 ]);9 await fileChooser.setFiles('/home/test/test.pdf');10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.exposeFunction('handleFileChooser', async (fileChooser) => {18 await fileChooser.setFiles('/home/test/test.pdf');19 });20 await page.evaluate(() => {21 document.querySelector('input[type=file]').addEventListener('click', () => {22 window.handleFileChooser(document.querySelector('input[type=file]').fileChooser);23 });24 });25 await browser.close();26})();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.exposeFunction('handleFileChooser', async (fileChooser) => {33 await fileChooser.setFiles('/home/test/test.pdf');34 });35 await page.evaluate(() => {36 document.querySelector('input[type=file]').addEventListener('click', () => {37 window.handleFileChooser(document.querySelector('input[type=file]').fileChooser);38 });39 });40 await browser.close();41})();42const { chromium } = require('playwright');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const fs = require('fs');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 await context._setFileChooserIntercepted(true);7 const page = await context.newPage();8 page.on('filechooser', async (fileChooser) => {9 console.log('File chooser opened');10 await fileChooser.setFiles('/home/username/Downloads/test.txt');11 });12 await page.click('input[type=file]');13 await page.waitForTimeout(10000);14 await browser.close();15})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**/*', route => route.continue());7 await page.evaluate(() => {8 document.querySelector('#file-input').addEventListener('click', () => {9 window.__setFileChooserIntercepted(true);10 });11 });12 const [fileChooser] = await Promise.all([13 page.waitForEvent('filechooser'),14 page.click('#file-input'),15 ]);16 await fileChooser.setFiles('C:\\Users\\test\\Desktop\\test.txt');17 await page.screenshot({ path: 'test.png' });18 await browser.close();19})();20Error: Protocol error (Page.setFileInputFiles): File not found at path C:\Users\test\Desktop\test.txt21const { 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 page.route('**/*', route => route.continue());27 await page.evaluate(() => {28 document.querySelector('#file-input').addEventListener('click', () => {29 window.__setFileChooserIntercepted(true);30 });31 });32 const [fileChooser] = await Promise.all([33 page.waitForEvent('filechooser'),34 page.click('#file-input'),35 ]);36 await fileChooser.setFiles('C:\\Users\\test\\Desktop\\test.txt');37 await page.screenshot({ path: 'test.png' });38 await browser.close();39})();40Error: Protocol error (Page.setFileInputFiles): File not found at path C:\Users\test\Desktop\test.txt41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2const { setFileChooserIntercepted } = require('playwright/lib/server/chromium/crPage');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await setFileChooserIntercepted(page, true);8 await page.setInputFiles('input[type="file"]', 'test.txt');9 await page.click('input[type="submit"]');10 await browser.close();11})();12 at new Promise (<anonymous>)13 at Object.helper (/home/username/Downloads/playwright-test/node_modules/playwright/lib/utils/utils.js:128:12)14 at CRPage.setFileChooserIntercepted (/home/username/Downloads/playwright-test/node_modules/playwright/lib/server/chromium/crPage.js:36:16)15 at setFileChooserIntercepted (/home/username/Downloads/playwright-test/node_modules/playwright/lib/server/chromium/crPage.js:35:11)16 at new Promise (<anonymous>)17 at ModuleJob.run (internal/modules/esm/module_job.js:152:23)18 at async Loader.import (internal/modules/esm/loader.js:166:24)

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2const fs = require('fs');3(async () => {4 const browser = await chromium.launch({5 });6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.setInputFiles('input[type="file"]', '/home/nikhil/Desktop/test.pdf');9 await page.click('input[type="submit"]');10 await browser.close();11})();12const {chromium} = require('playwright');13const fs = require('fs');14(async () => {15 const browser = await chromium.launch({16 });17 const context = await browser.newContext();18 const page = await context.newPage();19 await page.setInputFiles('input[type="file"]', '/home/nikhil/Desktop/test.pdf');20 await page.click('input[type="submit"]');21 await browser.close();22})();23const {chromium} = require('playwright');24const fs = require('fs');25(async () => {26 const browser = await chromium.launch({27 });28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.setInputFiles('input[type="file"]', '/home/nikhil/Desktop/test.pdf');31 await page.click('input[type="submit"]');32 await browser.close();33})();34const {chromium} = require('playwright');35const fs = require('fs');36(async () => {37 const browser = await chromium.launch({38 });39 const context = await browser.newContext();40 const page = await context.newPage();

Full Screen

Playwright tutorial

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

Chapters:

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

Run Playwright Internal automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful