Best JavaScript code snippet using playwright-internal
crPage.js
Source: crPage.js
...152 async navigateFrame(frame, url, referrer) {153 return this._sessionForFrame(frame)._navigate(frame, url, referrer);154 }155 async exposeBinding(binding) {156 await this._forAllFrameSessions(frame => frame._initBinding(binding));157 await Promise.all(this._page.frames().map(frame => frame.evaluateExpression(binding.source, false, {}).catch(e => {})));158 }159 async updateExtraHTTPHeaders() {160 await this._forAllFrameSessions(frame => frame._updateExtraHTTPHeaders(false));161 }162 async updateGeolocation() {163 await this._forAllFrameSessions(frame => frame._updateGeolocation(false));164 }165 async updateOffline() {166 await this._forAllFrameSessions(frame => frame._updateOffline(false));167 }168 async updateHttpCredentials() {169 await this._forAllFrameSessions(frame => frame._updateHttpCredentials(false));170 }171 async setEmulatedSize(emulatedSize) {172 (0, _utils.assert)(this._page._state.emulatedSize === emulatedSize);173 await this._mainFrameSession._updateViewport();174 }175 async bringToFront() {176 await this._mainFrameSession._client.send('Page.bringToFront');177 }178 async updateEmulateMedia() {179 await this._forAllFrameSessions(frame => frame._updateEmulateMedia(false));180 }181 async updateRequestInterception() {182 await this._forAllFrameSessions(frame => frame._updateRequestInterception());183 }184 async setFileChooserIntercepted(enabled) {185 await this._forAllFrameSessions(frame => frame._setFileChooserIntercepted(enabled));186 }187 async reload() {188 await this._mainFrameSession._client.send('Page.reload');189 }190 async _go(delta) {191 const history = await this._mainFrameSession._client.send('Page.getNavigationHistory');192 const entry = history.entries[history.currentIndex + delta];193 if (!entry) return false;194 await this._mainFrameSession._client.send('Page.navigateToHistoryEntry', {195 entryId: entry.id196 });197 return true;198 }199 goBack() {200 return this._go(-1);201 }202 goForward() {203 return this._go(+1);204 }205 async evaluateOnNewDocument(source, world = 'main') {206 await this._forAllFrameSessions(frame => frame._evaluateOnNewDocument(source, world));207 }208 async closePage(runBeforeUnload) {209 if (runBeforeUnload) await this._mainFrameSession._client.send('Page.close');else await this._browserContext._browser._closePage(this);210 }211 async setBackgroundColor(color) {212 await this._mainFrameSession._client.send('Emulation.setDefaultBackgroundColorOverride', {213 color214 });215 }216 async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport) {217 const {218 visualViewport219 } = await this._mainFrameSession._client.send('Page.getLayoutMetrics');220 if (!documentRect) {221 documentRect = {222 x: visualViewport.pageX + viewportRect.x,223 y: visualViewport.pageY + viewportRect.y,224 ..._helper.helper.enclosingIntSize({225 width: viewportRect.width / visualViewport.scale,226 height: viewportRect.height / visualViewport.scale227 })228 };229 } // When taking screenshots with documentRect (based on the page content, not viewport),230 // ignore current page scale.231 const clip = { ...documentRect,232 scale: viewportRect ? visualViewport.scale : 1233 };234 progress.throwIfAborted();235 const result = await this._mainFrameSession._client.send('Page.captureScreenshot', {236 format,237 quality,238 clip,239 captureBeyondViewport: !fitsViewport240 });241 return Buffer.from(result.data, 'base64');242 }243 async getContentFrame(handle) {244 return this._sessionForHandle(handle)._getContentFrame(handle);245 }246 async getOwnerFrame(handle) {247 return this._sessionForHandle(handle)._getOwnerFrame(handle);248 }249 isElementHandle(remoteObject) {250 return remoteObject.subtype === 'node';251 }252 async getBoundingBox(handle) {253 return this._sessionForHandle(handle)._getBoundingBox(handle);254 }255 async scrollRectIntoViewIfNeeded(handle, rect) {256 return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);257 }258 async setScreencastOptions(options) {259 if (options) {260 await this._mainFrameSession._startScreencast(this, {261 format: 'jpeg',262 quality: options.quality,263 maxWidth: options.width,264 maxHeight: options.height265 });266 } else {267 await this._mainFrameSession._stopScreencast(this);268 }269 }270 rafCountForStablePosition() {271 return 1;272 }273 async getContentQuads(handle) {274 return this._sessionForHandle(handle)._getContentQuads(handle);275 }276 async setInputFiles(handle, files) {277 await handle.evaluateInUtility(([injected, node, files]) => injected.setInputFiles(node, files), files);278 }279 async adoptElementHandle(handle, to) {280 return this._sessionForHandle(handle)._adoptElementHandle(handle, to);281 }282 async getAccessibilityTree(needle) {283 return (0, _crAccessibility.getAccessibilityTree)(this._mainFrameSession._client, needle);284 }285 async inputActionEpilogue() {286 await this._mainFrameSession._client.send('Page.enable').catch(e => {});287 }288 async pdf(options) {289 return this._pdf.generate(options);290 }291 coverage() {292 return this._coverage;293 }294 async getFrameElement(frame) {295 let parent = frame.parentFrame();296 if (!parent) throw new Error('Frame has been detached.');297 const parentSession = this._sessionForFrame(parent);298 const {299 backendNodeId300 } = await parentSession._client.send('DOM.getFrameOwner', {301 frameId: frame._id302 }).catch(e => {303 if (e instanceof Error && e.message.includes('Frame with the given id was not found.')) (0, _stackTrace.rewriteErrorMessage)(e, 'Frame has been detached.');304 throw e;305 });306 parent = frame.parentFrame();307 if (!parent) throw new Error('Frame has been detached.');308 return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());309 }310}311exports.CRPage = CRPage;312class FrameSession {313 // Marks the oopif session that remote -> local transition has happened in the parent.314 // See Target.detachedFromTarget handler for details.315 constructor(crPage, client, targetId, parentSession) {316 this._client = void 0;317 this._crPage = void 0;318 this._page = void 0;319 this._networkManager = void 0;320 this._contextIdToContext = new Map();321 this._eventListeners = [];322 this._targetId = void 0;323 this._firstNonInitialNavigationCommittedPromise = void 0;324 this._firstNonInitialNavigationCommittedFulfill = () => {};325 this._firstNonInitialNavigationCommittedReject = e => {};326 this._windowId = void 0;327 this._swappedIn = false;328 this._videoRecorder = null;329 this._screencastId = null;330 this._screencastClients = new Set();331 this._client = client;332 this._crPage = crPage;333 this._page = crPage._page;334 this._targetId = targetId;335 this._networkManager = new _crNetworkManager.CRNetworkManager(client, this._page, parentSession ? parentSession._networkManager : null);336 this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {337 this._firstNonInitialNavigationCommittedFulfill = f;338 this._firstNonInitialNavigationCommittedReject = r;339 });340 client.once(_crConnection.CRSessionEvents.Disconnected, () => {341 this._firstNonInitialNavigationCommittedReject(new Error('Page closed'));342 });343 }344 _isMainFrame() {345 return this._targetId === this._crPage._targetId;346 }347 _addRendererListeners() {348 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))]);349 }350 _addBrowserListeners() {351 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))]);352 }353 async _initialize(hasUIWindow) {354 if (hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) {355 const {356 windowId357 } = await this._client.send('Browser.getWindowForTarget');358 this._windowId = windowId;359 }360 let screencastOptions;361 if (this._isMainFrame() && this._crPage._browserContext._options.recordVideo && hasUIWindow) {362 const screencastId = (0, _utils.createGuid)();363 const outputFile = _path.default.join(this._crPage._browserContext._options.recordVideo.dir, screencastId + '.webm');364 screencastOptions = { // validateBrowserContextOptions ensures correct video size.365 ...this._crPage._browserContext._options.recordVideo.size,366 outputFile367 };368 await this._crPage._browserContext._ensureVideosPath(); // Note: it is important to start video recorder before sending Page.startScreencast,369 // and it is equally important to send Page.startScreencast before sending Runtime.runIfWaitingForDebugger.370 await this._createVideoRecorder(screencastId, screencastOptions);371 this._crPage.pageOrError().then(p => {372 if (p instanceof Error) this._stopVideoRecording().catch(() => {});373 });374 }375 let lifecycleEventsEnabled;376 if (!this._isMainFrame()) this._addRendererListeners();377 this._addBrowserListeners();378 const promises = [this._client.send('Page.enable'), this._client.send('Page.getFrameTree').then(({379 frameTree380 }) => {381 if (this._isMainFrame()) {382 this._handleFrameTree(frameTree);383 this._addRendererListeners();384 }385 const localFrames = this._isMainFrame() ? this._page.frames() : [this._page._frameManager.frame(this._targetId)];386 for (const frame of localFrames) {387 // Note: frames might be removed before we send these.388 this._client._sendMayFail('Page.createIsolatedWorld', {389 frameId: frame._id,390 grantUniveralAccess: true,391 worldName: UTILITY_WORLD_NAME392 });393 for (const binding of this._crPage._browserContext._pageBindings.values()) frame.evaluateExpression(binding.source, false, undefined).catch(e => {});394 for (const source of this._crPage._browserContext._evaluateOnNewDocumentSources) frame.evaluateExpression(source, false, undefined, 'main').catch(e => {});395 }396 const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ':';397 if (isInitialEmptyPage) {398 // Ignore lifecycle events for the initial empty page. It is never the final page399 // hence we are going to get more lifecycle updates after the actual navigation has400 // started (even if the target url is about:blank).401 lifecycleEventsEnabled.catch(e => {}).then(() => {402 this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));403 });404 } else {405 this._firstNonInitialNavigationCommittedFulfill();406 this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));407 }408 }), this._client.send('Log.enable', {}), lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', {409 enabled: true410 }), this._client.send('Runtime.enable', {}), this._client.send('Page.addScriptToEvaluateOnNewDocument', {411 source: '',412 worldName: UTILITY_WORLD_NAME413 }), this._networkManager.initialize(), this._client.send('Target.setAutoAttach', {414 autoAttach: true,415 waitForDebuggerOnStart: true,416 flatten: true417 })];418 if (this._isMainFrame()) promises.push(this._client.send('Emulation.setFocusEmulationEnabled', {419 enabled: true420 }));421 const options = this._crPage._browserContext._options;422 if (options.bypassCSP) promises.push(this._client.send('Page.setBypassCSP', {423 enabled: true424 }));425 if (options.ignoreHTTPSErrors) promises.push(this._client.send('Security.setIgnoreCertificateErrors', {426 ignore: true427 }));428 if (this._isMainFrame()) promises.push(this._updateViewport());429 if (options.hasTouch) promises.push(this._client.send('Emulation.setTouchEmulationEnabled', {430 enabled: true431 }));432 if (options.javaScriptEnabled === false) promises.push(this._client.send('Emulation.setScriptExecutionDisabled', {433 value: true434 }));435 if (options.userAgent || options.locale) promises.push(this._client.send('Emulation.setUserAgentOverride', {436 userAgent: options.userAgent || '',437 acceptLanguage: options.locale438 }));439 if (options.locale) promises.push(emulateLocale(this._client, options.locale));440 if (options.timezoneId) promises.push(emulateTimezone(this._client, options.timezoneId));441 promises.push(this._updateGeolocation(true));442 promises.push(this._updateExtraHTTPHeaders(true));443 promises.push(this._updateRequestInterception());444 promises.push(this._updateOffline(true));445 promises.push(this._updateHttpCredentials(true));446 promises.push(this._updateEmulateMedia(true));447 for (const binding of this._crPage._page.allBindings()) promises.push(this._initBinding(binding));448 for (const source of this._crPage._browserContext._evaluateOnNewDocumentSources) promises.push(this._evaluateOnNewDocument(source, 'main'));449 for (const source of this._crPage._page._evaluateOnNewDocumentSources) promises.push(this._evaluateOnNewDocument(source, 'main'));450 if (screencastOptions) promises.push(this._startVideoRecording(screencastOptions));451 promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));452 promises.push(this._firstNonInitialNavigationCommittedPromise);453 await Promise.all(promises);454 }455 dispose() {456 _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);457 this._networkManager.dispose();458 this._crPage._sessions.delete(this._targetId);459 }460 async _navigate(frame, url, referrer) {461 const response = await this._client.send('Page.navigate', {462 url,463 referrer,464 frameId: frame._id465 });466 if (response.errorText) throw new Error(`${response.errorText} at ${url}`);467 return {468 newDocumentId: response.loaderId469 };470 }471 _onLifecycleEvent(event) {472 if (this._eventBelongsToStaleFrame(event.frameId)) return;473 if (event.name === 'load') this._page._frameManager.frameLifecycleEvent(event.frameId, 'load');else if (event.name === 'DOMContentLoaded') this._page._frameManager.frameLifecycleEvent(event.frameId, 'domcontentloaded');474 }475 _onFrameStoppedLoading(frameId) {476 if (this._eventBelongsToStaleFrame(frameId)) return;477 this._page._frameManager.frameStoppedLoading(frameId);478 }479 _handleFrameTree(frameTree) {480 this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);481 this._onFrameNavigated(frameTree.frame, true);482 if (!frameTree.childFrames) return;483 for (const child of frameTree.childFrames) this._handleFrameTree(child);484 }485 _eventBelongsToStaleFrame(frameId) {486 const frame = this._page._frameManager.frame(frameId); // Subtree may be already gone because some ancestor navigation destroyed the oopif.487 if (!frame) return true; // When frame goes remote, parent process may still send some events488 // related to the local frame before it sends frameDetached.489 // In this case, we already have a new session for this frame, so events490 // in the old session should be ignored.491 const session = this._crPage._sessionForFrame(frame);492 return session && session !== this && !session._swappedIn;493 }494 _onFrameAttached(frameId, parentFrameId) {495 const frameSession = this._crPage._sessions.get(frameId);496 if (frameSession && frameId !== this._targetId) {497 // This is a remote -> local frame transition.498 frameSession._swappedIn = true;499 const frame = this._page._frameManager.frame(frameId); // Frame or even a whole subtree may be already gone, because some ancestor did navigate.500 if (frame) this._page._frameManager.removeChildFramesRecursively(frame);501 return;502 }503 if (parentFrameId && !this._page._frameManager.frame(parentFrameId)) {504 // Parent frame may be gone already because some ancestor frame navigated and505 // destroyed the whole subtree of some oopif, while oopif's process is still sending us events.506 // Be careful to not confuse this with "main frame navigated cross-process" scenario507 // where parentFrameId is null.508 return;509 }510 this._page._frameManager.frameAttached(frameId, parentFrameId);511 }512 _onFrameNavigated(framePayload, initial) {513 if (this._eventBelongsToStaleFrame(framePayload.id)) return;514 this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ''), framePayload.name || '', framePayload.loaderId, initial);515 if (!initial) this._firstNonInitialNavigationCommittedFulfill();516 }517 _onFrameRequestedNavigation(payload) {518 if (this._eventBelongsToStaleFrame(payload.frameId)) return;519 if (payload.disposition === 'currentTab') this._page._frameManager.frameRequestedNavigation(payload.frameId);520 }521 _onFrameNavigatedWithinDocument(frameId, url) {522 if (this._eventBelongsToStaleFrame(frameId)) return;523 this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);524 }525 _onFrameDetached(frameId, reason) {526 if (this._crPage._sessions.has(frameId)) {527 // This is a local -> remote frame transtion, where528 // Page.frameDetached arrives after Target.attachedToTarget.529 // We've already handled the new target and frame reattach - nothing to do here.530 return;531 }532 if (reason === 'swap') {533 // This is a local -> remote frame transtion, where534 // Page.frameDetached arrives before Target.attachedToTarget.535 // We should keep the frame in the tree, and it will be used for the new target.536 const frame = this._page._frameManager.frame(frameId);537 if (frame) this._page._frameManager.removeChildFramesRecursively(frame);538 return;539 } // Just a regular frame detach.540 this._page._frameManager.frameDetached(frameId);541 }542 _onExecutionContextCreated(contextPayload) {543 const frame = contextPayload.auxData ? this._page._frameManager.frame(contextPayload.auxData.frameId) : null;544 if (!frame || this._eventBelongsToStaleFrame(frame._id)) return;545 const delegate = new _crExecutionContext.CRExecutionContext(this._client, contextPayload);546 let worldName = null;547 if (contextPayload.auxData && !!contextPayload.auxData.isDefault) worldName = 'main';else if (contextPayload.name === UTILITY_WORLD_NAME) worldName = 'utility';548 const context = new dom.FrameExecutionContext(delegate, frame, worldName);549 context[contextDelegateSymbol] = delegate;550 if (worldName) frame._contextCreated(worldName, context);551 this._contextIdToContext.set(contextPayload.id, context);552 }553 _onExecutionContextDestroyed(executionContextId) {554 const context = this._contextIdToContext.get(executionContextId);555 if (!context) return;556 this._contextIdToContext.delete(executionContextId);557 context.frame._contextDestroyed(context);558 }559 _onExecutionContextsCleared() {560 for (const contextId of Array.from(this._contextIdToContext.keys())) this._onExecutionContextDestroyed(contextId);561 }562 _onAttachedToTarget(event) {563 const session = _crConnection.CRConnection.fromSession(this._client).session(event.sessionId);564 if (event.targetInfo.type === 'iframe') {565 // Frame id equals target id.566 const targetId = event.targetInfo.targetId;567 const frame = this._page._frameManager.frame(targetId);568 if (!frame) return; // Subtree may be already gone due to renderer/browser race.569 this._page._frameManager.removeChildFramesRecursively(frame);570 const frameSession = new FrameSession(this._crPage, session, targetId, this);571 this._crPage._sessions.set(targetId, frameSession);572 frameSession._initialize(false).catch(e => e);573 return;574 }575 if (event.targetInfo.type !== 'worker') {576 // Ideally, detaching should resume any target, but there is a bug in the backend.577 session._sendMayFail('Runtime.runIfWaitingForDebugger').then(() => {578 this._client._sendMayFail('Target.detachFromTarget', {579 sessionId: event.sessionId580 });581 });582 return;583 }584 const url = event.targetInfo.url;585 const worker = new _page.Worker(this._page, url);586 this._page._addWorker(event.sessionId, worker);587 session.once('Runtime.executionContextCreated', async event => {588 worker._createExecutionContext(new _crExecutionContext.CRExecutionContext(session, event.context));589 }); // This might fail if the target is closed before we initialize.590 session._sendMayFail('Runtime.enable');591 session._sendMayFail('Network.enable');592 session._sendMayFail('Runtime.runIfWaitingForDebugger');593 session.on('Runtime.consoleAPICalled', event => {594 const args = event.args.map(o => worker._existingExecutionContext.createHandle(o));595 this._page._addConsoleMessage(event.type, args, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));596 });597 session.on('Runtime.exceptionThrown', exception => this._page.emit(_page.Page.Events.PageError, (0, _crProtocolHelper.exceptionToError)(exception.exceptionDetails))); // TODO: attribute workers to the right frame.598 this._networkManager.instrumentNetworkEvents(session, this._page._frameManager.frame(this._targetId));599 }600 _onDetachedFromTarget(event) {601 // This might be a worker...602 this._page._removeWorker(event.sessionId); // ... or an oopif.603 const childFrameSession = this._crPage._sessions.get(event.targetId);604 if (!childFrameSession) return; // Usually, we get frameAttached in this session first and mark child as swappedIn.605 if (childFrameSession._swappedIn) {606 childFrameSession.dispose();607 return;608 } // However, sometimes we get detachedFromTarget before frameAttached.609 // In this case we don't know wheter this is a remote frame detach,610 // or just a remote -> local transition. In the latter case, frameAttached611 // is already inflight, so let's make a safe roundtrip to ensure it arrives.612 this._client.send('Page.enable').catch(e => null).then(() => {613 // Child was not swapped in - that means frameAttached did not happen and614 // this is remote detach rather than remote -> local swap.615 if (!childFrameSession._swappedIn) this._page._frameManager.frameDetached(event.targetId);616 childFrameSession.dispose();617 });618 }619 _onWindowOpen(event) {620 this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);621 }622 async _onConsoleAPI(event) {623 if (event.executionContextId === 0) {624 // DevTools protocol stores the last 1000 console messages. These625 // messages are always reported even for removed execution contexts. In626 // this case, they are marked with executionContextId = 0 and are627 // reported upon enabling Runtime agent.628 //629 // Ignore these messages since:630 // - there's no execution context we can use to operate with message631 // arguments632 // - these messages are reported before Playwright clients can subscribe633 // to the 'console'634 // page event.635 //636 // @see https://github.com/GoogleChrome/puppeteer/issues/3865637 return;638 }639 const context = this._contextIdToContext.get(event.executionContextId);640 if (!context) return;641 const values = event.args.map(arg => context.createHandle(arg));642 this._page._addConsoleMessage(event.type, values, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));643 }644 async _initBinding(binding) {645 await Promise.all([this._client.send('Runtime.addBinding', {646 name: binding.name647 }), this._client.send('Page.addScriptToEvaluateOnNewDocument', {648 source: binding.source649 })]);650 }651 async _onBindingCalled(event) {652 const pageOrError = await this._crPage.pageOrError();653 if (!(pageOrError instanceof Error)) {654 const context = this._contextIdToContext.get(event.executionContextId);655 if (context) await this._page._onBindingCalled(event.payload, context);656 }657 }658 _onDialog(event) {...
MVCController.jsx
Source: MVCController.jsx
...85 }86 if (!(this.app instanceof MVCApplication)) throw Error ('MVCController: Missing application reference');87 this.bind = (typeof this.bind == 'boolean' ? this.bind : true); 88 // ÐаÑÑинг ÑÑÑоки биндинга, иниÑиализаÑиÑ89 this._initBinding();90};9192inherit(MVCController, MVCObject);9394 // Ðа оÑнове ÑÑÑоки биндинга ÑоÑмиÑÑÐµÑ ÑÑÑÐ»ÐºÑ Ð½Ð° ÑодиÑелÑÑкий в оÑноÑении заданного клÑÑа обÑÐµÐºÑ (иÑполÑзÑеÑÑÑ Ð²95 // MVCApplication.addController() и MVCView.rebind())96 var _parseBind = function(obj, str) {97 var keys = str.split('.').slice(1);98 if (keys.length == 0) throw Error(localize(locales.ERR_BEDBIND, str));99 for (var i=0, o = obj; i<keys.length-1; i++) o = o[keys[i]];100 return { object:o, key:(keys[keys.length-1]).toString() };101}102103/**
...
cms.js
Source: cms.js
...300*/301var initialize_binding = function initialize_binding () {302 if (!CMS.contentxml) return false;303304 // _initBinding();305 if (CMS.binding) return CMS.binding;306307 var groups = {}, nodes = CMS.contentxml.documentElement.getElementsByTagName('group');308 for (var i = 0; i < nodes.length; i++) {309 var id = nodes[i].getAttribute('id');310311 groups[id] = {312 id: id,313 label: nodes[i].getAttribute('label'),314 entries: binding_entries(id, nodes[i]),315 _group: nodes[i]316 };317 }318
...
layout.js
Source: layout.js
...41 $.ajax({42 url: "/welcome/your_picks"43 }).done(function(data) {44 $("#your_picks_section").html(data);45 _initBinding();46 });47 $.ajax({48 url: "/welcome/twitter"49 }).done(function(data) {50 $("#twitter_section").html(data);51 });52 }53 54 /**55 * Binds the provider select box so that a user can change providers.56 * Called when the service type select box is changed.57 */58 function _providerBinding() {59 $("#choose_provider").on('change', function() {60 $("#stations").css('opacity','0.9');61 $("#stations").css('background-color','#CCC');62 $('#ajax-loader').show(); 63 var type = $("#service_type option:selected").val();64 var desc = $("#choose_provider option:selected").val(); 65 $.ajax({66 url: "/welcome/change_provider?",//type=" + type + "&desc=" + desc,67 data: { type: type, desc: desc } //"type=" + type + "desc=" + desc //....68 }).done(function(data) {69 $("#stations").html(data); //console.log(data)70 _regenYourPicks();71 }).fail(function(data) { // TODO: Should be something more user friendly72 alert("There was an error with the request. Sorry.");73 }).always(function() {74 $('#ajax-loader').hide();75 $("#stations").css('opacity','1');76 $("#stations").css('background-color','white');77 });78 79 });80 }81 82 83 /**84 * Does the initial binding of the colorboxes and like/dislike buttons.85 */86 function _initBinding() {87 $(".poster").hover(function(){88 if ($(this).data("bouncing") == false || $(this).data("bouncing") == undefined){89 $(this).effect("bounce", { distance: 5, times: 1 }, 500);90 $(this).data("bouncing", true);91 }92 },function () {93 $(this).data("bouncing", false);94 });95 96 $(".poster, .popBad, .popGood, .popTop").on('click', function() {97 _showOverlay(this);98 });99 100 $(".hide_media_button").on('click', function(event) {101 var liked = "";102 if (event.target.id == "hide_like") {103 liked = "true";104 } else if (event.target.id == "hide_dislike") {105 liked = "false";106 }107 108 var data = $(this).parent().attr('data-id').split(',');109 110 $.ajax({111 type: "GET",112 url: "/welcome/hide_media",113 data: {"like": liked, "media_type": data[0] , "media_id": data[1]}114 }).done(function(data) {115 $("#your_picks_section").html(data).slideDown(500).show();116 _initBinding();117 });118 });119 }120 121 /**122 * Binds the posters only, allowing them to bounce and be clicked.123 * Should work in any section with .posters 124 */125 function _posterBinding() {126 $(".poster").hover(function(){127 if ($(this).data("bouncing") == false || $(this).data("bouncing") == undefined){128 $(this).effect("bounce", { distance: 5, times: 1 }, 500);129 $(this).data("bouncing", true);130 }131 },function () {132 $(this).data("bouncing", false);133 });134 135 $(".poster").on('click', function() {136 _showOverlay(this);137 });138 }139 140 function _expandPhoto() {141 var overlay = document.createElement("div");142 overlay.setAttribute("id","overlay");143 overlay.setAttribute("class", "overlay");144 document.body.appendChild(overlay);145 }146 147 function _restore() {148 document.body.removeChild(document.getElementById("overlay"));149 }150 function _showOverlay(thiz) {151 $.ajax({152 url: $(thiz).attr('data-id') // get movie#show for this movie153 154 }).done(function(data) { 155 //console.log(data);156 $("#info_overlay").html(data);157 });158 159 $(thiz).colorbox({ 160 width:"800px",161 height:"650px",162 inline: true,163 href: "#info_overlay",164 speed: 500,165 onLoad:function() { 166 document.documentElement.style.overflow = "hidden";167 var id = $(thiz).attr('data-id');168 },169 onClosed:function() {170 $(".overlay_info").css("overflow", "hidden");171 $(".overlay_info").css("height", "200px");172 $("#overlay_more_info").show();173 document.documentElement.style.overflow = "auto";174 }175 })176 }177 return {178 /**179 * Public Methods (separated by commas)180 */181 documentReady: function() {182 var your_picks_times_forward = 0;183 var netflix_times_forward = 0;184 185 $('#type_type_key').hide();186 $('#service_type').change(function() {187 $('#type_type_key').fadeIn();188 });189 $('#ajax-loader').hide(); 190 191 $('#tv').prop('checked', true);192 $("#tv_show").prop('checked', true);193 $("#movie").prop('checked', true);194 195 196 $('#twitter_tab').click(function() {197 $('#twitter_section').slideDown('slow');198 });199 $('#facebook_tab').click(function() {200 $('#facebook_section').slideDown('slow');201 }); 202 $('#tv').click(function() {203 if ($(this).is(':checked')) {204 $('#tv_section').slideDown('slow');205 } else {206 $('#tv_section').slideUp('slow');207 }208 });209 210 $("#tv_show, #movie").click(function() {211 $("#your_picks_section").hide();212 $("#netflix_section").hide();213 your_picks_times_forward = netflix_times_forward = 0;214 _determineYourPrevious(your_picks_times_forward);215 //_determineNetflixPrevious(netflix_times_forward);216 217 var netflix_bool = $("#netflix").is(':checked');218 var movie_bool = $("#movie").is(':checked');219 var tv_show_bool = $("#tv_show").is(':checked');220 221 $.ajax({222 url: "/welcome/show_media?",223 data: { "tv_show": tv_show_bool, "movie": movie_bool, "netflix": netflix_bool } 224 }).done(function(data) {225 $("#your_picks_section").html(data);226 _initBinding();227 }).always(function() {228 $("#your_picks_section").show();229 _initBinding();230 });231 232 $.ajax({233 url: "/welcome/render_netflix"234 }).done(function(data) {235 $("#netflix_section").html(data);236 }).always(function() {237 if (netflix_bool) {238 $("#netflix_section").show();239 _posterBinding();240 }241 });242 });243 244 $('#netflix').click(function() {245 your_picks_times_forward = netflix_times_forward = 0;246 _determineYourPrevious(your_picks_times_forward);247 // _determineNetflixPrevious(netflix_times_forward);248 249 var netflix_checked = $("#netflix").is(':checked');250 var movie_checked = $("#movie").is(':checked');251 var tv_show_checked = $("#tv_show").is(':checked');252 253 if (netflix_checked) {254 $("#netflix_container").show();255 $("#your_picks_section").hide();256 }257 else {258 $("#netflix_section").hide();//('fast');259 $("#your_picks_section").hide(); //('fast'); //hide();260 $("#netflix_container").hide();261 }262 263 264 // change the media to reflect the netflix update265 $.ajax({266 url: "/welcome/show_media?",267 data: { "tv_show": tv_show_checked, "movie": movie_checked, "netflix": netflix_checked } 268 }).done(function(data) {269 $("#your_picks_section").html(data);270 }).always(function() {271 $("#your_picks_section").slideDown();272 _initBinding();273 // render the netflix section274 $.ajax({275 url: "/welcome/render_netflix"276 }).done(function(data) {277 $("#netflix_section").html(data);278 if (netflix_checked) {279 $("#netflix_section").slideDown();280 }281 //TODO: The binding here may not need to be the initBinding() function, but instead a new netflixBinding, or something282 //_initBinding();283 _posterBinding();284 });285 });286 287 288 });289 290 291 $('#hulu').click(function() {292 if ($(this).is(':checked')) {293 $("#hulu_section").slideDown('slow');294 //$("#netflix_section").slideDown('slow');295 }296 else {297 $("#hulu_section").slideUp('slow');298 }299 });300 301 302 $(".chzn-select").chosen(); 303 $(".chzn-select-deselect").chosen({allow_single_deselect:true});304 305 306 // shows a different selection of picks when the view more link is pressed307 $("#view_more").on('click', function(event) {308 var yourPicksHeight = $("#your_picks_container").height();309 $("#your_picks_container").css('height', yourPicksHeight);310 $.ajax({311 url: "/welcome/rotate_picks?forward=true&your_picks=true"312 313 }).done(function(data) {314 event.preventDefault();315 $("#your_picks_section").hide();316 $("#your_picks_section").html(data).slideDown(500).show();317 _initBinding();318 _determineYourPrevious(++your_picks_times_forward);319 });320 });321 322 $("#view_more_netflix").on('click', function(event) {323 var netflixPicksHeight = $("#netflix_container").height();324 $("#netflix_container").css("height", netflixPicksHeight);325 $("#netflix_section").hide();326 $.ajax({327 url: "/welcome/rotate_picks?forward=true&netflix=true"328 }).done(function(data) {329 $("#netflix_section").html(data).show();330 _posterBinding();331 //_determineNetflixPrevious(++netflix_times_forward);332 }).fail(function() {333 $("#previous_netflix").hide();334 $("#view_more_netflix").hide();335 });336 });337 338 $("#overlay_more_info").on('click', function() {339 $(".overlay_info").css("overflow", "auto");340 $(".overlay_info").css("height", "100%");341 $("#overlay_more_info").hide();342 });343 344 $("#previous_picks").on('click', function(event) {345 $.ajax({346 url: "/welcome/rotate_picks?forward=false&your_picks=true"347 }).done(function(data) {348 $("#your_picks_section").hide();349 $("#your_picks_section").html(data).slideDown(500).show();350 _initBinding();351 _determineYourPrevious(--your_picks_times_forward);352 });353 });354 355 $("#previous_netflix").on('click', function() {356 $("#netflix_section").hide();357 $.ajax({358 url: "/welcome/rotate_picks?forward=false&netflix=true"359 }).done(function(data) {360 console.log(data)361 $("#netflix_section").html(data).show();362 _posterBinding();363 //_determineNetflixPrevious(--netflix_times_forward);364 }).fail(function() {365 $("#previous_netflix").hide();366 $("#view_more_netflix").hide();367 });368 });369 370 371 372 373 /**374 * Update the shown providers when the service type option is changed.375 */376 $("#service_type").on('change', function() {377 var type = $("#service_type option:selected").text();378 $.ajax({379 url: "/welcome/get_providers?type=" + type380 }).done(function(data) {381 $("#choose_provider").hide();382 $("#choose_provider").html(data).show();383 });384 385 });386 387 388 /**389 * When the update zip code box is updated, stop the default action390 * and turn it into an ajax action.391 */392 $("#update_zip").on('submit', function() {393 var newZip = $("#new_zip").val();394 if ( newZip.length != 5 || !(/^(\d)+$/.test(newZip)) ) {395 alert("There was a problem with the new zip code.");396 return false;397 }398 399 $("#choose_provider").hide().empty();400 $("#stations").css('opacity','0.9');401 $("#stations").css('background-color','#CCC');402 $('#ajax-loader').show(); 403 404 $.ajax({405 url: "/welcome/update_zip",406 data: { zip_code: newZip }407 }).done(function(data) {408 $("#stations").html(data);409 _regenYourPicks();410 }).fail(function(data) {411 alert("There was a failure. This cannot ever happen.");412 }).always(function() {413 $('#ajax-loader').hide();414 $("#stations").css('opacity','1');415 $("#stations").css('background-color','white');416 });417 418 // prevent the default form action from occurring 419 return false;420 });421 422 423 _initBinding();424 _providerBinding();425 _regenYourPicks();426 }427 };...
view.js
Source: view.js
...117 this.setOptions(options);118 this.opts = this.options;119 this.container = options.container;120 this._init();121 //this._initBinding();122 return this;123 },124 /**125 * init126 * @param {Object} opts127 * @return {void}128 * @private129 */130 _init: function(opts) {131 _log.debug('init');132 opts = this.opts;133 this.index = 0;134 this.views = [];135 //this.layout = ui.node[opts.name];136 this._initContainer();137 if (opts.toolbar) {138 opts.toolbar.lang = this.options.lang;139 this._initToolbar(opts.toolbar);140 }141 if (opts.menus) {142 this._initMenus();143 }144 this._initEvents();145 if (opts.scroller) {146 this._initScroller();147 }148 this._initView();149 //this.binding = this._initBinding();150 this.fireEvent('initReady');151 },152 /**153 * init view154 * @return {void}155 * @private156 */157 _initView: function() {158 _log.debug('_initView');159 this.isOpen = true;160 this.visible = true;161 /*if (this.options.foot) {162 this.container._initFoot();163 }*/...
team_chooser.js
Source: team_chooser.js
...22 };23 },24 componentWillMount: function () {25 const self = this;26 self._initBinding();27 SchoolHelper.loadActiveSchoolInfo(this);28 },29 _initBinding: function() {30 const self = this,31 binding = self.getDefaultBinding();32 binding.set('viewMode', Immutable.fromJS('close'));33 self._getTeams().then(teams => {34 teams.sort((teamA, teamB)=>{35 if (teamA.name.toLowerCase() > teamB.name.toLowerCase()) {return 1}36 if (teamA.name.toLowerCase() < teamB.name.toLowerCase()) {return -1}37 });38 binding.set('teams', Immutable.fromJS(teams));39 }40 );...
component.js
Source: component.js
...38 this.fireEvent('init');39 this._initOptions();40 this._initElement();41 this._initEvents();42 this._initBinding();43 return this;44 },45 /**46 * Setter for the state of the component47 * @param {string} state active/disable etc...48 */49 setState: function(state) {50 _log.debug('setState', state, this);51 this.element.removeClass('state-' + this.state);52 if (state) {53 this.element.addClass('state-' + state);54 }55 this.state = state;56 this.fireEvent('state', state);...
Using AI Code Generation
1const { _initBinding } = require('playwright-core/lib/server/chromium/crBrowser');2const { BrowserServer } = require('playwright-core/lib/server/browserServer');3const { BrowserContext } = require('playwright-core/lib/server/browserContext');4const { Browser } = require('playwright-core/lib/server/browser');5const { Page } = require('playwright-core/lib/server/page');6const { helper } = require('playwright-core/lib/helper');7const { Connection } = require('playwright-core/lib/server/connection');8const { ConnectionTransport } = require('playwright-core/lib/server/connectionTransport');9const { EventEmitter } = require('events');10const transport = new ConnectionTransport();11const connection = new Connection('foo', transport, new EventEmitter());12const browser = new Browser(connection, null, null, null, new EventEmitter());13const context = new BrowserContext(connection, browser, null, null, null, null, null, null, new EventEmitter());14const server = new BrowserServer(browser, null, null, null);15const page = new Page(connection, context, null, null);16const h = new helper.Helper();17const fakeMethod = () => { console.log('fakeMethod called'); };18const fakeObject = { fakeMethod };19_initBinding(page, 'foo', fakeObject);20page._delegate._foo.fakeMethod();
Using AI Code Generation
1const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');2const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');3const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');4const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');5const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');6const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');7const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');8const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');9const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');10const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');11const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');12const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');13const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');14const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');15const { _initBinding } = require('playwright/lib/server/chromium/crBrowser');16const {
Using AI Code Generation
1const { _initBinding } = require('playwright/lib/server/playwright.js');2const { Playwright } = require('playwright/lib/server/playwright.js');3const { BrowserType } = require('playwright/lib/server/browserType.js');4const { Browser } = require('playwright/lib/server/browser.js');5const { BrowserContext } = require('playwright/lib/server/browserContext.js');6const { Page } = require('playwright/lib/server/page.js');7const { Electron } = require('playwright/lib/server/electron.js');8const { ElectronApplication } = require('playwright/lib/server/electronApplication.js');9const { ElectronBrowser } = require('playwright/lib/server/electronBrowser.js');10const { ElectronBrowserContext } = require('playwright/lib/server/electronBrowserContext.js');11const { ElectronPage } = require('playwright/lib/server/electronPage.js');12const { chromium } = require('playwright');13const playwright = new Playwright();14playwright._initBinding();15const browserType = new BrowserType(playwright, 'chromium');16browserType._initBinding();17const browser = new Browser(browserType, '1234');18browser._initBinding();19const browserContext = new BrowserContext(browser, '1234');20browserContext._initBinding();21const page = new Page(browserContext, '1234');22page._initBinding();23const electron = new Electron();24electron._initBinding();25const electronApplication = new ElectronApplication(electron, '1234');26electronApplication._initBinding();27const electronBrowser = new ElectronBrowser(electron, '1234');28electronBrowser._initBinding();
Using AI Code Generation
1const { _initBinding } = require('playwright/lib/server/browserType');2const { BrowserType } = require('playwright/lib/server/browserType');3const { Browser } = require('playwright/lib/server/browser');4const { Page } = require('playwright/lib/server/page');5const { BrowserContext } = require('playwright/lib/server/browserContext');6const { ElementHandle } = require('playwright/lib/server/dom');7const { Frame } = require('playwright/lib/server/frames');8const { JSHandle } = require('playwright/lib/server/jsHandle');9const { CDPSession } = require('playwright/lib/server/cdpsession');10async function main() {11 const browser = await _initBinding(BrowserType, 'chromium', {12 });13 const context = await browser.newContext();14 const page = await context.newPage();15 const frame = page.mainFrame();16 const element = await frame.$('div');17 const handle = await element.evaluateHandle(() => document.body);18 const cdpsession = await page.target().createCDPSession();19 console.log('cdpsession', cdpsession);20}21main();22cdpsession CDPSession {23 _target: Target {24 _browserContext: BrowserContext {25 _browser: Browser {26 _browserType: BrowserType {27 },
Using AI Code Generation
1const pw = require('playwright');2const { ChromiumBrowserContext } = require('playwright/lib/server/chromium/chromiumBrowser');3const { WebKitBrowserContext } = require('playwright/lib/server/webkit/webKitBrowser');4const { FirefoxBrowserContext } = require('playwright/lib/server/firefox/firefoxBrowser');5const { BrowserContext } = require('playwright/lib/server/browserContext');6ChromiumBrowserContext.prototype._initBinding = function(binding) {7 if (this._pageBindings.has(binding.name))8 throw new Error(`Failed to add page binding with name ${binding.name}: window['${binding.name}'] already exists!`);9 this._pageBindings.set(binding.name, binding);10 for (const page of this.pages())11 page._onBindingCalled({name: binding.name, source: binding.source, needsHandle: binding.needsHandle});12};13WebKitBrowserContext.prototype._initBinding = function(binding) {14 if (this._pageBindings.has(binding.name))15 throw new Error(`Failed to add page binding with name ${binding.name}: window['${binding.name}'] already exists!`);16 this._pageBindings.set(binding.name, binding);17 for (const page of this.pages())18 page._onBindingCalled({name: binding.name, source: binding.source, needsHandle: binding.needsHandle});19};20FirefoxBrowserContext.prototype._initBinding = function(binding) {21 if (this._pageBindings.has(binding.name))22 throw new Error(`Failed to add page binding with name ${binding.name}: window['${binding.name}'] already exists!`);23 this._pageBindings.set(binding.name, binding);24 for (const page of this.pages())25 page._onBindingCalled({name: binding.name, source: binding.source, needsHandle: binding.needsHandle});26};27BrowserContext.prototype._initBinding = function(binding) {28 if (this._pageBindings.has(binding.name))29 throw new Error(`Failed to add page binding with name ${binding.name}: window['${binding.name}'] already exists!`);30 this._pageBindings.set(binding.name, binding);31 for (const page of this.pages())32 page._onBindingCalled({name: binding.name, source: binding.source, needsHandle: binding.needsHandle});33};34(async () => {35 const browser = await pw.chromium.launch();36 const context = await browser.newContext();
Using AI Code Generation
1const { _initBinding } = require('playwright/lib/server/frames');2const { Frame } = require('playwright/lib/server/frames');3const { Page } = require('playwright/lib/server/page');4const { BrowserContext } = require('playwright/lib/server/browserContext');5const { Browser } = require('playwright/lib/server/browser');6const { BrowserType } = require('playwright/lib/server/browserType');7const { Connection } = require('playwright/lib/server/connection');8const { Transport } = require('playwright/lib/server/transport');9const { EventEmitter } = require('events');10const { WebSocketTransport } = require('playwright/lib/server/webSocketTransport');11const { debugLogger } = require('playwright/lib/utils/debugLogger');12const { helper } = require('playwright/lib/helper');13const { createTransport } = require('playwright/lib/server/transport');14const { createWebSocketTransport } = require('playwright/lib/server/webSocketTransport');15const { createPlaywright } = require('playwright/lib/server/playwright');16const { chromium } = require('playwright');17const { PageProxy } = require('playwright/lib/server/proxyServer');18const { Transport, createTransport } = require('playwright/lib/server/transport');19const { WebSocketTransport, createWebSocketTransport } = require('playwright/lib/server/webSocketTransport');20const { Connection } = require('playwright/lib/server/connection');21const { debugLogger } = require('playwright/lib/utils/debugLogger');22const { helper } = require('playwright/lib/helper');23const { BrowserContext } = require('playwright/lib/server/browserContext');24const { Browser } = require('playwright/lib/server/browser');25const { BrowserType } = require('playwright/lib/server/browserType');26const { Page } = require('playwright/lib/server/page');27const { Frame } = require('playwright/lib/server/frames');28const { Worker } = require('playwright/lib/server/worker');29const { ConsoleMessage } = require('playwright/lib/server/consoleMessage');30const { Dialog } = require('playwright/lib/server/dialog');31const { Download } = require('playwright/lib/server/download');32const { ElementHandle } = require('playwright/lib/server/elementHandler');33const { FileChooser } = require('playwright/lib/server/fileChooser');34const { JSHandle } = require('playwright/lib/server/jsHandle');35const { NetworkManager } = require('playwright/lib
Using AI Code Generation
1const { Playwright } = require('playwright');2const { Page } = require('playwright/lib/page');3Page.prototype._initBinding = function (name, callback, isFunction) {4 this._pageBindings.set(name, { callback, isFunction });5 this._channel._send('initBinding', { name });6};7const { Playwright } = require('playwright');8const { Page } = require('playwright/lib/page');9Page.prototype.initBinding = function (name, callback, isFunction) {10 this._pageBindings.set(name, { callback, isFunction });11 this._channel._send('initBinding', { name });12};13const { Playwright } = require('playwright');14const { Page } = require('playwright/lib/page');15Page.prototype.initBinding = function (name, callback, isFunction) {16 this._pageBindings.set(name, { callback, isFunction });17 this._channel._send('initBinding', { name });18};19const { Playwright } = require('playwright');20const { Page } = require('playwright/lib/page');21Page.prototype.initBinding = function (name, callback, isFunction) {22 this._pageBindings.set(name, { callback, isFunction });23 this._channel._send('initBinding', { name });24};25const { Playwright } = require('playwright');26const { Page } = require('playwright/lib/page');27Page.prototype.initBinding = function (name, callback, isFunction) {28 this._pageBindings.set(name, { callback, isFunction });29 this._channel._send('initBinding', { name });30};31const { Playwright } = require('playwright');32const { Page } = require('playwright/lib/page');33Page.prototype.initBinding = function (name, callback, isFunction) {34 this._pageBindings.set(name, { callback, isFunction });35 this._channel._send('initBinding', { name });36};37const { Playwright } = require('playwright');38const { Page } = require('playwright/lib/page');
Using AI Code Generation
1const binding = require('@playwright/test/lib/server/playwright')._initBinding();2const browserType = binding._createBrowserType('chromium', {3 executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',4});5const browser = await browserType._launch({6 executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',7 env: {},8});9const context = await browser._newContext({10 extraHTTPHeaders: {},11});12const page = await context.newPage();
Using AI Code Generation
1const { _initBinding } = require('playwright/lib/server/browserContext');2_initBinding('name', 'path/to/binding.js');3module.exports = function({page, context, electron}) {4 context.exposeBinding('name', (source, args) => {5 });6};7await page.evaluate(() => {8 window[name].call(null, 'args');9});
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!