How to use verifyLifecycle method in Playwright Internal

Best JavaScript code snippet using playwright-internal

frames.js

Source:frames.js Github

copy

Full Screen

...452 return controller.run(progress => this._goto(progress, constructedNavigationURL, options), this._page._timeoutSettings.navigationTimeout(options));453 }454 async _goto(progress, url, options) {455 return this.raceNavigationAction(async () => {456 const waitUntil = verifyLifecycle('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);457 progress.log(`navigating to "${url}", waiting until "${waitUntil}"`);458 const headers = this._page._state.extraHTTPHeaders || [];459 const refererHeader = headers.find(h => h.name.toLowerCase() === 'referer');460 let referer = refererHeader ? refererHeader.value : undefined;461 if (options.referer !== undefined) {462 if (referer !== undefined && referer !== options.referer) throw new Error('"referer" is already specified as extra HTTP header');463 referer = options.referer;464 }465 url = _helper.helper.completeUserURL(url);466 const sameDocument = _helper.helper.waitForEvent(progress, this, Frame.Events.Navigation, e => !e.newDocument);467 const navigateResult = await this._page._delegate.navigateFrame(this, url, referer);468 let event;469 if (navigateResult.newDocumentId) {470 sameDocument.dispose();471 event = await _helper.helper.waitForEvent(progress, this, Frame.Events.Navigation, event => {472 // We are interested either in this specific document, or any other document that473 // did commit and replaced the expected document.474 return event.newDocument && (event.newDocument.documentId === navigateResult.newDocumentId || !event.error);475 }).promise;476 if (event.newDocument.documentId !== navigateResult.newDocumentId) {477 // This is just a sanity check. In practice, new navigation should478 // cancel the previous one and report "request cancelled"-like error.479 throw new Error('Navigation interrupted by another one');480 }481 if (event.error) throw event.error;482 } else {483 event = await sameDocument.promise;484 }485 if (!this._subtreeLifecycleEvents.has(waitUntil)) await _helper.helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, e => e === waitUntil).promise;486 const request = event.newDocument ? event.newDocument.request : undefined;487 const response = request ? request._finalRequest().response() : null;488 await this._page._doSlowMo();489 return response;490 });491 }492 async _waitForNavigation(progress, options) {493 const waitUntil = verifyLifecycle('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);494 progress.log(`waiting for navigation until "${waitUntil}"`);495 const navigationEvent = await _helper.helper.waitForEvent(progress, this, Frame.Events.Navigation, event => {496 // Any failed navigation results in a rejection.497 if (event.error) return true;498 progress.log(` navigated to "${this._url}"`);499 return true;500 }).promise;501 if (navigationEvent.error) throw navigationEvent.error;502 if (!this._subtreeLifecycleEvents.has(waitUntil)) await _helper.helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, e => e === waitUntil).promise;503 const request = navigationEvent.newDocument ? navigationEvent.newDocument.request : undefined;504 return request ? request._finalRequest().response() : null;505 }506 async _waitForLoadState(progress, state) {507 const waitUntil = verifyLifecycle('state', state);508 if (!this._subtreeLifecycleEvents.has(waitUntil)) await _helper.helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, e => e === waitUntil).promise;509 }510 async frameElement() {511 return this._page._delegate.getFrameElement(this);512 }513 _context(world) {514 if (this._detached) throw new Error(`Execution Context is not available in detached frame "${this.url()}" (are you trying to evaluate?)`);515 return this._contextData.get(world).contextPromise;516 }517 _mainContext() {518 return this._context('main');519 }520 _existingMainContext() {521 var _this$_contextData$ge2;522 return ((_this$_contextData$ge2 = this._contextData.get('main')) === null || _this$_contextData$ge2 === void 0 ? void 0 : _this$_contextData$ge2.context) || null;523 }524 _utilityContext() {525 return this._context('utility');526 }527 async evaluateExpressionHandleAndWaitForSignals(expression, isFunction, arg, world = 'main') {528 const context = await this._context(world);529 const handle = await context.evaluateExpressionHandleAndWaitForSignals(expression, isFunction, arg);530 if (world === 'main') await this._page._doSlowMo();531 return handle;532 }533 async evaluateExpression(expression, isFunction, arg, world = 'main') {534 const context = await this._context(world);535 const value = await context.evaluateExpression(expression, isFunction, arg);536 if (world === 'main') await this._page._doSlowMo();537 return value;538 }539 async evaluateExpressionAndWaitForSignals(expression, isFunction, arg, world = 'main') {540 const context = await this._context(world);541 const value = await context.evaluateExpressionAndWaitForSignals(expression, isFunction, arg);542 if (world === 'main') await this._page._doSlowMo();543 return value;544 }545 async querySelector(selector, options) {546 _debugLogger.debugLogger.log('api', ` finding element using the selector "${selector}"`);547 return this._page.selectors.query(this, selector, options);548 }549 async waitForSelector(metadata, selector, options = {}) {550 const controller = new _progress.ProgressController(metadata, this);551 if (options.visibility) throw new Error('options.visibility is not supported, did you mean options.state?');552 if (options.waitFor && options.waitFor !== 'visible') throw new Error('options.waitFor is not supported, did you mean options.state?');553 const {554 state = 'visible'555 } = options;556 if (!['attached', 'detached', 'visible', 'hidden'].includes(state)) throw new Error(`state: expected one of (attached|detached|visible|hidden)`);557 const info = this._page.parseSelector(selector, options);558 const task = dom.waitForSelectorTask(info, state, options.omitReturnValue);559 return controller.run(async progress => {560 progress.log(`waiting for selector "${selector}"${state === 'attached' ? '' : ' to be ' + state}`);561 while (progress.isRunning()) {562 const result = await this._scheduleRerunnableHandleTask(progress, info.world, task);563 if (!result.asElement()) {564 result.dispose();565 return null;566 }567 if (options.__testHookBeforeAdoptNode) await options.__testHookBeforeAdoptNode();568 try {569 const handle = result.asElement();570 const adopted = await handle._adoptTo(await this._mainContext());571 return adopted;572 } catch (e) {573 // Navigated while trying to adopt the node.574 if (js.isJavaScriptErrorInEvaluate(e)) throw e;575 result.dispose();576 }577 }578 return null;579 }, this._page._timeoutSettings.timeout(options));580 }581 async dispatchEvent(metadata, selector, type, eventInit = {}, options = {}) {582 await this._scheduleRerunnableTask(metadata, selector, (progress, element, data) => {583 progress.injectedScript.dispatchEvent(element, data.type, data.eventInit);584 }, {585 type,586 eventInit587 }, {588 mainWorld: true,589 ...options590 });591 await this._page._doSlowMo();592 }593 async evalOnSelectorAndWaitForSignals(selector, strict, expression, isFunction, arg) {594 const handle = await this.querySelector(selector, {595 strict596 });597 if (!handle) throw new Error(`Error: failed to find element matching selector "${selector}"`);598 const result = await handle.evaluateExpressionAndWaitForSignals(expression, isFunction, true, arg);599 handle.dispose();600 return result;601 }602 async evalOnSelectorAllAndWaitForSignals(selector, expression, isFunction, arg) {603 const arrayHandle = await this._page.selectors._queryArray(this, selector);604 const result = await arrayHandle.evaluateExpressionAndWaitForSignals(expression, isFunction, true, arg);605 arrayHandle.dispose();606 return result;607 }608 async querySelectorAll(selector) {609 return this._page.selectors._queryAll(this, selector, undefined, true610 /* adoptToMain */611 );612 }613 async content() {614 try {615 const context = await this._utilityContext();616 return await context.evaluate(() => {617 let retVal = '';618 if (document.doctype) retVal = new XMLSerializer().serializeToString(document.doctype);619 if (document.documentElement) retVal += document.documentElement.outerHTML;620 return retVal;621 });622 } catch (e) {623 if (js.isJavaScriptErrorInEvaluate(e) || (0, _protocolError.isSessionClosedError)(e)) throw e;624 throw new Error(`Unable to retrieve content because the page is navigating and changing the content.`);625 }626 }627 async setContent(metadata, html, options = {}) {628 const controller = new _progress.ProgressController(metadata, this);629 return controller.run(progress => this.raceNavigationAction(async () => {630 const waitUntil = options.waitUntil === undefined ? 'load' : options.waitUntil;631 progress.log(`setting frame content, waiting until "${waitUntil}"`);632 const tag = `--playwright--set--content--${this._id}--${++this._setContentCounter}--`;633 const context = await this._utilityContext();634 const lifecyclePromise = new Promise((resolve, reject) => {635 this._page._frameManager._consoleMessageTags.set(tag, () => {636 // Clear lifecycle right after document.open() - see 'tag' below.637 this._onClearLifecycle();638 this._waitForLoadState(progress, waitUntil).then(resolve).catch(reject);639 });640 });641 const contentPromise = context.evaluate(({642 html,643 tag644 }) => {645 window.stop();646 document.open();647 console.debug(tag); // eslint-disable-line no-console648 document.write(html);649 document.close();650 }, {651 html,652 tag653 });654 await Promise.all([contentPromise, lifecyclePromise]);655 await this._page._doSlowMo();656 }), this._page._timeoutSettings.navigationTimeout(options));657 }658 name() {659 return this._name || '';660 }661 url() {662 return this._url;663 }664 parentFrame() {665 return this._parentFrame;666 }667 childFrames() {668 return Array.from(this._childFrames);669 }670 async addScriptTag(params) {671 const {672 url = null,673 content = null,674 type = ''675 } = params;676 if (!url && !content) throw new Error('Provide an object with a `url`, `path` or `content` property');677 const context = await this._mainContext();678 return this._raceWithCSPError(async () => {679 if (url !== null) return (await context.evaluateHandle(addScriptUrl, {680 url,681 type682 })).asElement();683 const result = (await context.evaluateHandle(addScriptContent, {684 content: content,685 type686 })).asElement(); // Another round trip to the browser to ensure that we receive CSP error messages687 // (if any) logged asynchronously in a separate task on the content main thread.688 if (this._page._delegate.cspErrorsAsynchronousForInlineScipts) await context.evaluate(() => true);689 return result;690 });691 async function addScriptUrl(params) {692 const script = document.createElement('script');693 script.src = params.url;694 if (params.type) script.type = params.type;695 const promise = new Promise((res, rej) => {696 script.onload = res;697 script.onerror = e => rej(typeof e === 'string' ? new Error(e) : new Error(`Failed to load script at ${script.src}`));698 });699 document.head.appendChild(script);700 await promise;701 return script;702 }703 function addScriptContent(params) {704 const script = document.createElement('script');705 script.type = params.type || 'text/javascript';706 script.text = params.content;707 let error = null;708 script.onerror = e => error = e;709 document.head.appendChild(script);710 if (error) throw error;711 return script;712 }713 }714 async addStyleTag(params) {715 const {716 url = null,717 content = null718 } = params;719 if (!url && !content) throw new Error('Provide an object with a `url`, `path` or `content` property');720 const context = await this._mainContext();721 return this._raceWithCSPError(async () => {722 if (url !== null) return (await context.evaluateHandle(addStyleUrl, url)).asElement();723 return (await context.evaluateHandle(addStyleContent, content)).asElement();724 });725 async function addStyleUrl(url) {726 const link = document.createElement('link');727 link.rel = 'stylesheet';728 link.href = url;729 const promise = new Promise((res, rej) => {730 link.onload = res;731 link.onerror = rej;732 });733 document.head.appendChild(link);734 await promise;735 return link;736 }737 async function addStyleContent(content) {738 const style = document.createElement('style');739 style.type = 'text/css';740 style.appendChild(document.createTextNode(content));741 const promise = new Promise((res, rej) => {742 style.onload = res;743 style.onerror = rej;744 });745 document.head.appendChild(style);746 await promise;747 return style;748 }749 }750 async _raceWithCSPError(func) {751 const listeners = [];752 let result;753 let error;754 let cspMessage;755 const actionPromise = func().then(r => result = r).catch(e => error = e);756 const errorPromise = new Promise(resolve => {757 listeners.push(_eventsHelper.eventsHelper.addEventListener(this._page, _page.Page.Events.Console, message => {758 if (message.type() === 'error' && message.text().includes('Content Security Policy')) {759 cspMessage = message;760 resolve();761 }762 }));763 });764 await Promise.race([actionPromise, errorPromise]);765 _eventsHelper.eventsHelper.removeEventListeners(listeners);766 if (cspMessage) throw new Error(cspMessage.text());767 if (error) throw error;768 return result;769 }770 async _retryWithProgressIfNotConnected(progress, selector, strict, action) {771 const info = this._page.parseSelector(selector, {772 strict773 });774 while (progress.isRunning()) {775 progress.log(`waiting for selector "${selector}"`);776 const task = dom.waitForSelectorTask(info, 'attached');777 const handle = await this._scheduleRerunnableHandleTask(progress, info.world, task);778 const element = handle.asElement();779 progress.cleanupWhenAborted(() => {780 // Do not await here to avoid being blocked, either by stalled781 // page (e.g. alert) or unresolved navigation in Chromium.782 element.dispose();783 });784 const result = await action(element);785 element.dispose();786 if (result === 'error:notconnected') {787 progress.log('element was detached from the DOM, retrying');788 continue;789 }790 return result;791 }792 return undefined;793 }794 async _retryWithSelectorIfNotConnected(controller, selector, options, action) {795 return controller.run(async progress => {796 return this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => action(progress, handle));797 }, this._page._timeoutSettings.timeout(options));798 }799 async click(metadata, selector, options) {800 const controller = new _progress.ProgressController(metadata, this);801 return controller.run(async progress => {802 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._click(progress, options)));803 }, this._page._timeoutSettings.timeout(options));804 }805 async dblclick(metadata, selector, options = {}) {806 const controller = new _progress.ProgressController(metadata, this);807 return controller.run(async progress => {808 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._dblclick(progress, options)));809 }, this._page._timeoutSettings.timeout(options));810 }811 async dragAndDrop(metadata, source, target, options = {}) {812 const controller = new _progress.ProgressController(metadata, this);813 await controller.run(async progress => {814 await dom.assertDone(await this._retryWithProgressIfNotConnected(progress, source, options.strict, async handle => {815 return handle._retryPointerAction(progress, 'move and down', false, async point => {816 await this._page.mouse.move(point.x, point.y);817 await this._page.mouse.down();818 }, { ...options,819 position: options.sourcePosition,820 timeout: progress.timeUntilDeadline()821 });822 }));823 await dom.assertDone(await this._retryWithProgressIfNotConnected(progress, target, options.strict, async handle => {824 return handle._retryPointerAction(progress, 'move and up', false, async point => {825 await this._page.mouse.move(point.x, point.y);826 await this._page.mouse.up();827 }, { ...options,828 position: options.targetPosition,829 timeout: progress.timeUntilDeadline()830 });831 }));832 }, this._page._timeoutSettings.timeout(options));833 }834 async tap(metadata, selector, options) {835 const controller = new _progress.ProgressController(metadata, this);836 return controller.run(async progress => {837 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._tap(progress, options)));838 }, this._page._timeoutSettings.timeout(options));839 }840 async fill(metadata, selector, value, options) {841 const controller = new _progress.ProgressController(metadata, this);842 return controller.run(async progress => {843 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._fill(progress, value, options)));844 }, this._page._timeoutSettings.timeout(options));845 }846 async focus(metadata, selector, options = {}) {847 const controller = new _progress.ProgressController(metadata, this);848 await this._retryWithSelectorIfNotConnected(controller, selector, options, (progress, handle) => handle._focus(progress));849 await this._page._doSlowMo();850 }851 async textContent(metadata, selector, options = {}) {852 return this._scheduleRerunnableTask(metadata, selector, (progress, element) => element.textContent, undefined, options);853 }854 async innerText(metadata, selector, options = {}) {855 return this._scheduleRerunnableTask(metadata, selector, (progress, element) => {856 if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml') throw progress.injectedScript.createStacklessError('Node is not an HTMLElement');857 return element.innerText;858 }, undefined, options);859 }860 async innerHTML(metadata, selector, options = {}) {861 return this._scheduleRerunnableTask(metadata, selector, (progress, element) => element.innerHTML, undefined, options);862 }863 async getAttribute(metadata, selector, name, options = {}) {864 return this._scheduleRerunnableTask(metadata, selector, (progress, element, data) => element.getAttribute(data.name), {865 name866 }, options);867 }868 async inputValue(metadata, selector, options = {}) {869 return this._scheduleRerunnableTask(metadata, selector, (progress, element) => {870 if (element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA' && element.nodeName !== 'SELECT') throw progress.injectedScript.createStacklessError('Node is not an <input>, <textarea> or <select> element');871 return element.value;872 }, undefined, options);873 }874 async _elementState(metadata, selector, state, options = {}) {875 const result = await this._scheduleRerunnableTask(metadata, selector, (progress, element, data) => {876 const injected = progress.injectedScript;877 return injected.elementState(element, data.state);878 }, {879 state880 }, options);881 return dom.throwRetargetableDOMError(result);882 }883 async isVisible(metadata, selector, options = {}) {884 const controller = new _progress.ProgressController(metadata, this);885 return controller.run(async progress => {886 progress.log(` checking visibility of "${selector}"`);887 const element = await this.querySelector(selector, options);888 return element ? await element.isVisible() : false;889 }, this._page._timeoutSettings.timeout({}));890 }891 async isHidden(metadata, selector, options = {}) {892 return !(await this.isVisible(metadata, selector, options));893 }894 async isDisabled(metadata, selector, options = {}) {895 return this._elementState(metadata, selector, 'disabled', options);896 }897 async isEnabled(metadata, selector, options = {}) {898 return this._elementState(metadata, selector, 'enabled', options);899 }900 async isEditable(metadata, selector, options = {}) {901 return this._elementState(metadata, selector, 'editable', options);902 }903 async isChecked(metadata, selector, options = {}) {904 return this._elementState(metadata, selector, 'checked', options);905 }906 async hover(metadata, selector, options = {}) {907 const controller = new _progress.ProgressController(metadata, this);908 return controller.run(async progress => {909 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._hover(progress, options)));910 }, this._page._timeoutSettings.timeout(options));911 }912 async selectOption(metadata, selector, elements, values, options = {}) {913 const controller = new _progress.ProgressController(metadata, this);914 return controller.run(async progress => {915 return await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._selectOption(progress, elements, values, options));916 }, this._page._timeoutSettings.timeout(options));917 }918 async setInputFiles(metadata, selector, files, options = {}) {919 const controller = new _progress.ProgressController(metadata, this);920 return controller.run(async progress => {921 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._setInputFiles(progress, files, options)));922 }, this._page._timeoutSettings.timeout(options));923 }924 async type(metadata, selector, text, options = {}) {925 const controller = new _progress.ProgressController(metadata, this);926 return controller.run(async progress => {927 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._type(progress, text, options)));928 }, this._page._timeoutSettings.timeout(options));929 }930 async press(metadata, selector, key, options = {}) {931 const controller = new _progress.ProgressController(metadata, this);932 return controller.run(async progress => {933 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._press(progress, key, options)));934 }, this._page._timeoutSettings.timeout(options));935 }936 async check(metadata, selector, options = {}) {937 const controller = new _progress.ProgressController(metadata, this);938 return controller.run(async progress => {939 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._setChecked(progress, true, options)));940 }, this._page._timeoutSettings.timeout(options));941 }942 async uncheck(metadata, selector, options = {}) {943 const controller = new _progress.ProgressController(metadata, this);944 return controller.run(async progress => {945 return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options.strict, handle => handle._setChecked(progress, false, options)));946 }, this._page._timeoutSettings.timeout(options));947 }948 async waitForTimeout(metadata, timeout) {949 const controller = new _progress.ProgressController(metadata, this);950 return controller.run(async () => {951 await new Promise(resolve => setTimeout(resolve, timeout));952 });953 }954 async expect(metadata, selector, options) {955 const controller = new _progress.ProgressController(metadata, this);956 const querySelectorAll = options.expression === 'to.have.count' || options.expression.endsWith('.array');957 const mainWorld = options.expression === 'to.have.property';958 return await this._scheduleRerunnableTaskWithController(controller, selector, (progress, element, options, elements, continuePolling) => {959 if (!element) {960 var _options$expectedText;961 // expect(locator).toBeHidden() passes when there is no element.962 if (!options.isNot && options.expression === 'to.be.hidden') return {963 matches: true964 }; // expect(locator).not.toBeVisible() passes when there is no element.965 if (options.isNot && options.expression === 'to.be.visible') return {966 matches: false967 }; // expect(listLocator).toHaveText([]) passes when there are no elements matching.968 // expect(listLocator).not.toHaveText(['foo']) passes when there are no elements matching.969 const expectsEmptyList = ((_options$expectedText = options.expectedText) === null || _options$expectedText === void 0 ? void 0 : _options$expectedText.length) === 0;970 if (options.expression.endsWith('.array') && expectsEmptyList !== options.isNot) return {971 matches: expectsEmptyList972 }; // When none of the above applies, keep waiting for the element.973 return continuePolling;974 }975 const {976 matches,977 received978 } = progress.injectedScript.expect(progress, element, options, elements);979 if (matches === options.isNot) {980 // Keep waiting in these cases:981 // expect(locator).conditionThatDoesNotMatch982 // expect(locator).not.conditionThatDoesMatch983 progress.setIntermediateResult(received);984 if (!Array.isArray(received)) progress.log(` unexpected value "${received}"`);985 return continuePolling;986 } // Reached the expected state!987 return {988 matches,989 received990 };991 }, options, {992 strict: true,993 querySelectorAll,994 mainWorld,995 omitAttached: true,996 logScale: true,997 ...options998 }).catch(e => {999 if (js.isJavaScriptErrorInEvaluate(e)) throw e; // Q: Why not throw upon isSessionClosedError(e) as in other places?1000 // A: We want user to receive a friendly message containing the last intermediate result.1001 return {1002 received: controller.lastIntermediateResult(),1003 matches: options.isNot,1004 log: metadata.log1005 };1006 });1007 }1008 async _waitForFunctionExpression(metadata, expression, isFunction, arg, options, world = 'main') {1009 const controller = new _progress.ProgressController(metadata, this);1010 if (typeof options.pollingInterval === 'number') (0, _utils.assert)(options.pollingInterval > 0, 'Cannot poll with non-positive interval: ' + options.pollingInterval);1011 expression = js.normalizeEvaluationExpression(expression, isFunction);1012 const task = injectedScript => injectedScript.evaluateHandle((injectedScript, {1013 expression,1014 isFunction,1015 polling,1016 arg1017 }) => {1018 const predicate = arg => {1019 let result = self.eval(expression);1020 if (isFunction === true) {1021 result = result(arg);1022 } else if (isFunction === false) {1023 result = result;1024 } else {1025 // auto detect.1026 if (typeof result === 'function') result = result(arg);1027 }1028 return result;1029 };1030 if (typeof polling !== 'number') return injectedScript.pollRaf((progress, continuePolling) => predicate(arg) || continuePolling);1031 return injectedScript.pollInterval(polling, (progress, continuePolling) => predicate(arg) || continuePolling);1032 }, {1033 expression,1034 isFunction,1035 polling: options.pollingInterval,1036 arg1037 });1038 return controller.run(progress => this._scheduleRerunnableHandleTask(progress, world, task), this._page._timeoutSettings.timeout(options));1039 }1040 async waitForFunctionValueInUtility(progress, pageFunction) {1041 const expression = `() => {1042 const result = (${pageFunction})();1043 if (!result)1044 return result;1045 return JSON.stringify(result);1046 }`;1047 const handle = await this._waitForFunctionExpression((0, _instrumentation.internalCallMetadata)(), expression, true, undefined, {1048 timeout: progress.timeUntilDeadline()1049 }, 'utility');1050 return JSON.parse(handle.rawValue());1051 }1052 async title() {1053 const context = await this._utilityContext();1054 return context.evaluate(() => document.title);1055 }1056 _onDetached() {1057 this._stopNetworkIdleTimer();1058 this._detached = true;1059 this._detachedCallback();1060 for (const data of this._contextData.values()) {1061 for (const rerunnableTask of data.rerunnableTasks) rerunnableTask.terminate(new Error('waitForFunction failed: frame got detached.'));1062 }1063 if (this._parentFrame) this._parentFrame._childFrames.delete(this);1064 this._parentFrame = null;1065 }1066 async _scheduleRerunnableTask(metadata, selector, body, taskData, options = {}) {1067 const controller = new _progress.ProgressController(metadata, this);1068 return this._scheduleRerunnableTaskWithController(controller, selector, body, taskData, options);1069 }1070 async _scheduleRerunnableTaskWithController(controller, selector, body, taskData, options = {}) {1071 const info = this._page.parseSelector(selector, options);1072 const callbackText = body.toString();1073 const data = this._contextData.get(options.mainWorld ? 'main' : info.world);1074 return controller.run(async progress => {1075 progress.log(`waiting for selector "${selector}"`);1076 const rerunnableTask = new RerunnableTask(data, progress, injectedScript => {1077 return injectedScript.evaluateHandle((injected, {1078 info,1079 taskData,1080 callbackText,1081 querySelectorAll,1082 logScale,1083 omitAttached,1084 snapshotName1085 }) => {1086 const callback = injected.eval(callbackText);1087 const poller = logScale ? injected.pollLogScale.bind(injected) : injected.pollRaf.bind(injected);1088 let markedElements = new Set();1089 return poller((progress, continuePolling) => {1090 let element;1091 let elements = [];1092 if (querySelectorAll) {1093 elements = injected.querySelectorAll(info.parsed, document);1094 element = elements[0];1095 progress.logRepeating(` selector resolved to ${elements.length} element${elements.length === 1 ? '' : 's'}`);1096 } else {1097 element = injected.querySelector(info.parsed, document, info.strict);1098 elements = element ? [element] : [];1099 if (element) progress.logRepeating(` selector resolved to ${injected.previewNode(element)}`);1100 }1101 if (!element && !omitAttached) return continuePolling;1102 if (snapshotName) {1103 const previouslyMarkedElements = markedElements;1104 markedElements = new Set(elements);1105 for (const e of previouslyMarkedElements) {1106 if (!markedElements.has(e)) e.removeAttribute('__playwright_target__');1107 }1108 for (const e of markedElements) {1109 if (!previouslyMarkedElements.has(e)) e.setAttribute('__playwright_target__', snapshotName);1110 }1111 }1112 return callback(progress, element, taskData, elements, continuePolling);1113 });1114 }, {1115 info,1116 taskData,1117 callbackText,1118 querySelectorAll: options.querySelectorAll,1119 logScale: options.logScale,1120 omitAttached: options.omitAttached,1121 snapshotName: progress.metadata.afterSnapshot1122 });1123 }, true);1124 if (this._detached) rerunnableTask.terminate(new Error('Frame got detached.'));1125 if (data.context) rerunnableTask.rerun(data.context);1126 return await rerunnableTask.promise;1127 }, this._page._timeoutSettings.timeout(options));1128 }1129 _scheduleRerunnableHandleTask(progress, world, task) {1130 const data = this._contextData.get(world);1131 const rerunnableTask = new RerunnableTask(data, progress, task, false1132 /* returnByValue */1133 );1134 if (this._detached) rerunnableTask.terminate(new Error('waitForFunction failed: frame got detached.'));1135 if (data.context) rerunnableTask.rerun(data.context);1136 return rerunnableTask.handlePromise;1137 }1138 _setContext(world, context) {1139 const data = this._contextData.get(world);1140 data.context = context;1141 if (context) {1142 data.contextResolveCallback.call(null, context);1143 for (const rerunnableTask of data.rerunnableTasks) rerunnableTask.rerun(context);1144 } else {1145 data.contextPromise = new Promise(fulfill => {1146 data.contextResolveCallback = fulfill;1147 });1148 }1149 }1150 _contextCreated(world, context) {1151 const data = this._contextData.get(world); // In case of multiple sessions to the same target, there's a race between1152 // connections so we might end up creating multiple isolated worlds.1153 // We can use either.1154 if (data.context) this._setContext(world, null);1155 this._setContext(world, context);1156 }1157 _contextDestroyed(context) {1158 for (const [world, data] of this._contextData) {1159 if (data.context === context) this._setContext(world, null);1160 }1161 }1162 _startNetworkIdleTimer() {1163 (0, _utils.assert)(!this._networkIdleTimer); // We should not start a timer and report networkidle in detached frames.1164 // This happens at least in Firefox for child frames, where we may get requestFinished1165 // after the frame was detached - probably a race in the Firefox itself.1166 if (this._firedLifecycleEvents.has('networkidle') || this._detached) return;1167 this._networkIdleTimer = setTimeout(() => this._onLifecycleEvent('networkidle'), 500);1168 }1169 _stopNetworkIdleTimer() {1170 if (this._networkIdleTimer) clearTimeout(this._networkIdleTimer);1171 this._networkIdleTimer = undefined;1172 }1173 async extendInjectedScript(source, arg) {1174 const context = await this._context('main');1175 const injectedScriptHandle = await context.injectedScript();1176 return injectedScriptHandle.evaluateHandle((injectedScript, {1177 source,1178 arg1179 }) => {1180 return injectedScript.extend(source, arg);1181 }, {1182 source,1183 arg1184 });1185 }1186}1187exports.Frame = Frame;1188Frame.Events = {1189 Navigation: 'navigation',1190 AddLifecycle: 'addlifecycle',1191 RemoveLifecycle: 'removelifecycle'1192};1193class RerunnableTask {1194 constructor(data, progress, task, returnByValue) {1195 this.promise = void 0;1196 this.handlePromise = void 0;1197 this._task = void 0;1198 this._progress = void 0;1199 this._returnByValue = void 0;1200 this._contextData = void 0;1201 this._task = task;1202 this._progress = progress;1203 this._returnByValue = returnByValue;1204 if (returnByValue) this.promise = new _async.ManualPromise();else this.handlePromise = new _async.ManualPromise();1205 this._contextData = data;1206 this._contextData.rerunnableTasks.add(this);1207 }1208 terminate(error) {1209 this._reject(error);1210 }1211 _resolve(value) {1212 if (this.promise) this.promise.resolve(value);1213 if (this.handlePromise) this.handlePromise.resolve(value);1214 }1215 _reject(error) {1216 if (this.promise) this.promise.reject(error);1217 if (this.handlePromise) this.handlePromise.reject(error);1218 }1219 async rerun(context) {1220 try {1221 const injectedScript = await context.injectedScript();1222 const pollHandler = new dom.InjectedScriptPollHandler(this._progress, await this._task(injectedScript));1223 const result = this._returnByValue ? await pollHandler.finish() : await pollHandler.finishHandle();1224 this._contextData.rerunnableTasks.delete(this);1225 this._resolve(result);1226 } catch (e) {1227 if (js.isJavaScriptErrorInEvaluate(e) || (0, _protocolError.isSessionClosedError)(e)) {1228 this._contextData.rerunnableTasks.delete(this);1229 this._reject(e);1230 } // We will try again in the new execution context.1231 }1232 }1233}1234class SignalBarrier {1235 constructor(progress) {1236 this._progress = void 0;1237 this._protectCount = 0;1238 this._promise = new _async.ManualPromise();1239 this._progress = progress;1240 this.retain();1241 }1242 waitFor() {1243 this.release();1244 return this._promise;1245 }1246 async addFrameNavigation(frame) {1247 // Auto-wait top-level navigations only.1248 if (frame.parentFrame()) return;1249 this.retain();1250 const waiter = _helper.helper.waitForEvent(null, frame, Frame.Events.Navigation, e => {1251 if (!e.error && this._progress) this._progress.log(` navigated to "${frame._url}"`);1252 return true;1253 });1254 await Promise.race([frame._page._disconnectedPromise, frame._page._crashedPromise, frame._detachedPromise, waiter.promise]).catch(e => {});1255 waiter.dispose();1256 this.release();1257 }1258 retain() {1259 ++this._protectCount;1260 }1261 release() {1262 --this._protectCount;1263 if (!this._protectCount) this._promise.resolve();1264 }1265}1266function verifyLifecycle(name, waitUntil) {1267 if (waitUntil === 'networkidle0') waitUntil = 'networkidle';1268 if (!types.kLifecycleEvents.has(waitUntil)) throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle)`);1269 return waitUntil;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { verifyLifecycle } = require('playwright/lib/server/verifyLifecycle');2const { launch } = require('playwright');3(async () => {4 const browser = await launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await verifyLifecycle(page);8 await page.screenshot({ path: 'example.png' });9 await browser.close();10})();

Full Screen

Using AI Code Generation

copy

Full Screen

1import { verifyLifecycle } from 'playwright/lib/server/chromium/crBrowser';2const browser = await chromium.launch();3const page = await browser.newPage();4await browser.close();5import { verifyLifecycle } from 'playwright/lib/server/chromium/crBrowser';6const browser = await chromium.launch();7const context = await browser.newContext();8const page = await context.newPage();9await context.close();10await browser.close();11import { verifyLifecycle } from 'playwright/lib/server/chromium/crBrowser';12const browser = await chromium.launch();13const context = await browser.newContext();14const page = await context.newPage();15await context.close();16await browser.close();17import { verifyLifecycle } from 'playwright/lib/server/chromium/crBrowser';18const browser = await chromium.launch();19const context = await browser.newContext();20const page = await context.newPage();21await context.close();22await browser.close();23import { verifyLifecycle } from 'playwright/lib/server/chromium/crBrowser';24const browser = await chromium.launch();25const context = await browser.newContext();26const page = await context.newPage();27await context.close();28await browser.close();29import { verifyLifecycle } from 'playwright/lib/server/chromium/crBrowser';30const browser = await chromium.launch();31const context = await browser.newContext();32const page = await context.newPage();33await context.close();34await browser.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { verifyLifecycle } = require('playwright-core/lib/server/browserContext');2const { chromium } = require('playwright-core');3const { test } = require('@playwright/test');4test('verify lifecycle', async ({}) => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 verifyLifecycle(context);8 await browser.close();9});10const { verifyLifecycle } = require('playwright-core/lib/server/browserContext');11const { chromium } = require('playwright-core');12const { test } = require('@playwright/test');13test('verify lifecycle', async ({}) => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 verifyLifecycle(context);17 await context.close();18 await browser.close();19});20const { verifyLifecycle } = require('playwright-core/lib/server/browserContext');21const { chromium } = require('playwright-core');22const { test } = require('@playwright/test');23test('verify lifecycle', async ({}) => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 verifyLifecycle(context);28 await page.close();29 await context.close();30 await browser.close();31});32PASS test.js (5s)33 ✓ verify lifecycle (5s)34const { verifyLifecycle }

Full Screen

Using AI Code Generation

copy

Full Screen

1import { chromium, verifyLifecycle } from "playwright";2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await verifyLifecycle(page, "domcontentloaded");7 await browser.close();8})();9import { chromium, verifyLifecycle } from "playwright";10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await verifyLifecycle(page, "load");15 await browser.close();16})();17import { chromium, verifyLifecycle } from "playwright";18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 const frame = page.mainFrame();23 await verifyLifecycle(frame, "load");24 await browser.close();25})();26import { chromium, verifyLifecycle } from "playwright";27(async () => {28 const browser = await chromium.launch();29 const context = await browser.newContext();30 const page = await context.newPage();31 await page.route("**/*", (route) => route.fulfill({ body: "Hello" }));32 const [popup] = await Promise.all([33 verifyLifecycle(page.waitForEvent("popup"), "load"),34 page.click("text=About"),35 ]);36 await browser.close();37})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { verifyLifecycle } = require('playwright/lib/utils/lifecycle');2const { chromium } = require('playwright');3const browser = await chromium.launch();4verifyLifecycle(browser, 'Browser');5await browser.close();6const { verifyLifecycle } = require('playwright/lib/utils/lifecycle');7const { chromium } = require('playwright');8const browser = await chromium.launch();9const page = await browser.newPage();10verifyLifecycle(page, 'Page');11await page.close();12await browser.close();13const { verifyLifecycle } = require('playwright/lib/utils/lifecycle');14const { chromium } = require('playwright');15const browser = await chromium.launch();16const page = await browser.newPage();17const context = await page.context();18verifyLifecycle(context, 'BrowserContext');19await context.close();20await page.close();21await browser.close();22const { verifyLifecycle } = require('playwright/lib/utils/lifecycle');23const { chromium } = require('playwright');24const browser = await chromium.launch();25const page = await browser.newPage();26const context = await page.context();27const frame = await page.frame();28verifyLifecycle(frame, 'Frame');29await frame.close();30await context.close();31await page.close();32await browser.close();33const { verifyLifecycle } = require('playwright/lib/utils/lifecycle');34const { chromium } = require('playwright');35const browser = await chromium.launch();36const page = await browser.newPage();37const context = await page.context();38const frame = await page.frame();39const jsHandle = await frame.evaluateHandle(() => document.body);40verifyLifecycle(jsHandle, 'JSHandle');41await jsHandle.dispose();42await frame.close();43await context.close();44await page.close();45await browser.close();46const { verifyLifecycle } = require('playwright/lib/utils/lifecycle');47const { chromium } = require('playwright');48const browser = await chromium.launch();49const page = await browser.newPage();50const context = await page.context();51const frame = await page.frame();52const jsHandle = await frame.evaluateHandle(() => document.body);53const elementHandle = jsHandle.asElement();54verifyLifecycle(elementHandle, 'ElementHandle');55await elementHandle.dispose();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2const { verifyLifecycle } = Playwright._internalApi;3(async () => {4 const browser = await verifyLifecycle.launch();5 const context = await verifyLifecycle.newContext(browser);6 const page = await verifyLifecycle.newPage(context);7 await verifyLifecycle.closePage(page);8 await verifyLifecycle.closeContext(context);9 await verifyLifecycle.closeBrowser(browser);10})();

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