How to use _grantPermissions method in Playwright Internal

Best JavaScript code snippet using playwright-internal

wkPage.js

Source:wkPage.js Github

copy

Full Screen

...109 }));110 promises.push(this._updateViewport());111 promises.push(this.updateHttpCredentials());112 if (this._browserContext._permissions.size) {113 for (const [key, value] of this._browserContext._permissions) promises.push(this._grantPermissions(key, value));114 }115 if (this._browserContext._options.recordVideo) {116 const outputFile = _path.default.join(this._browserContext._options.recordVideo.dir, (0, _utils.createGuid)() + '.webm');117 promises.push(this._browserContext._ensureVideosPath().then(() => {118 return this._startVideo({ // validateBrowserContextOptions ensures correct video size.119 ...this._browserContext._options.recordVideo.size,120 outputFile121 });122 }));123 }124 await Promise.all(promises);125 }126 _setSession(session) {127 _eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);128 this._session = session;129 this.rawKeyboard.setSession(session);130 this.rawMouse.setSession(session);131 this._addSessionListeners();132 this._workers.setSession(session);133 } // This method is called for provisional targets as well. The session passed as the parameter134 // may be different from the current session and may be destroyed without becoming current.135 async _initializeSession(session, provisional, resourceTreeHandler) {136 await this._initializeSessionMayThrow(session, resourceTreeHandler).catch(e => {137 // Provisional session can be disposed at any time, for example due to new navigation initiating138 // a new provisional page.139 if (provisional && session.isDisposed()) return; // Swallow initialization errors due to newer target swap in,140 // since we will reinitialize again.141 if (this._session === session) throw e;142 });143 }144 async _initializeSessionMayThrow(session, resourceTreeHandler) {145 const [, frameTree] = await Promise.all([// Page agent must be enabled before Runtime.146 session.send('Page.enable'), session.send('Page.getResourceTree')]);147 resourceTreeHandler(frameTree);148 const promises = [// Resource tree should be received before first execution context.149 session.send('Runtime.enable'), session.send('Page.createUserWorld', {150 name: UTILITY_WORLD_NAME151 }).catch(_ => {}), // Worlds are per-process152 session.send('Console.enable'), session.send('Network.enable'), this._workers.initializeSession(session)];153 if (this._page._needsRequestInterception()) {154 promises.push(session.send('Network.setInterceptionEnabled', {155 enabled: true156 }));157 promises.push(session.send('Network.addInterception', {158 url: '.*',159 stage: 'request',160 isRegex: true161 }));162 }163 const contextOptions = this._browserContext._options;164 if (contextOptions.userAgent) promises.push(session.send('Page.overrideUserAgent', {165 value: contextOptions.userAgent166 }));167 if (this._page._state.mediaType || this._page._state.colorScheme || this._page._state.reducedMotion) promises.push(WKPage._setEmulateMedia(session, this._page._state.mediaType, this._page._state.colorScheme, this._page._state.reducedMotion));168 const bootstrapScript = this._calculateBootstrapScript();169 if (bootstrapScript.length) promises.push(session.send('Page.setBootstrapScript', {170 source: bootstrapScript171 }));172 this._page.frames().map(frame => frame.evaluateExpression(bootstrapScript, false, undefined).catch(e => {}));173 if (contextOptions.bypassCSP) promises.push(session.send('Page.setBypassCSP', {174 enabled: true175 }));176 if (this._page._state.emulatedSize) {177 promises.push(session.send('Page.setScreenSizeOverride', {178 width: this._page._state.emulatedSize.screen.width,179 height: this._page._state.emulatedSize.screen.height180 }));181 }182 promises.push(this.updateEmulateMedia());183 promises.push(session.send('Network.setExtraHTTPHeaders', {184 headers: (0, _utils.headersArrayToObject)(this._calculateExtraHTTPHeaders(), false185 /* lowerCase */186 )187 }));188 if (contextOptions.offline) promises.push(session.send('Network.setEmulateOfflineState', {189 offline: true190 }));191 promises.push(session.send('Page.setTouchEmulationEnabled', {192 enabled: !!contextOptions.hasTouch193 }));194 if (contextOptions.timezoneId) {195 promises.push(session.send('Page.setTimeZone', {196 timeZone: contextOptions.timezoneId197 }).catch(e => {198 throw new Error(`Invalid timezone ID: ${contextOptions.timezoneId}`);199 }));200 }201 promises.push(session.send('Page.overrideSetting', {202 setting: 'DeviceOrientationEventEnabled',203 value: contextOptions.isMobile204 }));205 promises.push(session.send('Page.overrideSetting', {206 setting: 'FullScreenEnabled',207 value: !contextOptions.isMobile208 }));209 promises.push(session.send('Page.overrideSetting', {210 setting: 'NotificationsEnabled',211 value: !contextOptions.isMobile212 }));213 promises.push(session.send('Page.overrideSetting', {214 setting: 'PointerLockEnabled',215 value: !contextOptions.isMobile216 }));217 promises.push(session.send('Page.overrideSetting', {218 setting: 'InputTypeMonthEnabled',219 value: contextOptions.isMobile220 }));221 promises.push(session.send('Page.overrideSetting', {222 setting: 'InputTypeWeekEnabled',223 value: contextOptions.isMobile224 }));225 await Promise.all(promises);226 }227 _onDidCommitProvisionalTarget(event) {228 const {229 oldTargetId,230 newTargetId231 } = event;232 (0, _utils.assert)(this._provisionalPage);233 (0, _utils.assert)(this._provisionalPage._session.sessionId === newTargetId, 'Unknown new target: ' + newTargetId);234 (0, _utils.assert)(this._session.sessionId === oldTargetId, 'Unknown old target: ' + oldTargetId);235 const newSession = this._provisionalPage._session;236 this._provisionalPage.commit();237 this._provisionalPage.dispose();238 this._provisionalPage = null;239 this._setSession(newSession);240 }241 _onTargetDestroyed(event) {242 const {243 targetId,244 crashed245 } = event;246 if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) {247 this._provisionalPage._session.dispose(false);248 this._provisionalPage.dispose();249 this._provisionalPage = null;250 } else if (this._session.sessionId === targetId) {251 this._session.dispose(false);252 _eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);253 if (crashed) {254 this._session.markAsCrashed();255 this._page._didCrash();256 }257 }258 }259 didClose() {260 this._page._didClose();261 }262 dispose(disconnected) {263 this._pageProxySession.dispose(disconnected);264 _eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);265 _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);266 if (this._session) this._session.dispose(disconnected);267 if (this._provisionalPage) {268 this._provisionalPage._session.dispose(disconnected);269 this._provisionalPage.dispose();270 this._provisionalPage = null;271 }272 this._page._didDisconnect();273 this._firstNonInitialNavigationCommittedReject(new Error('Page closed'));274 }275 dispatchMessageToSession(message) {276 this._pageProxySession.dispatchMessage(message);277 }278 handleProvisionalLoadFailed(event) {279 if (!this._initializedPage) {280 this._firstNonInitialNavigationCommittedReject(new Error('Initial load failed'));281 return;282 }283 if (!this._provisionalPage) return;284 let errorText = event.error;285 if (errorText.includes('cancelled')) errorText += '; maybe frame was detached?';286 this._page._frameManager.frameAbortedNavigation(this._page.mainFrame()._id, errorText, event.loaderId);287 }288 handleWindowOpen(event) {289 (0, _utils.debugAssert)(!this._nextWindowOpenPopupFeatures);290 this._nextWindowOpenPopupFeatures = event.windowFeatures;291 }292 async pageOrError() {293 return this._pagePromise;294 }295 async _onTargetCreated(event) {296 const {297 targetInfo298 } = event;299 const session = new _wkConnection.WKSession(this._pageProxySession.connection, targetInfo.targetId, `Target closed`, message => {300 this._pageProxySession.send('Target.sendMessageToTarget', {301 message: JSON.stringify(message),302 targetId: targetInfo.targetId303 }).catch(e => {304 session.dispatchMessage({305 id: message.id,306 error: {307 message: e.message308 }309 });310 });311 });312 (0, _utils.assert)(targetInfo.type === 'page', 'Only page targets are expected in WebKit, received: ' + targetInfo.type);313 if (!targetInfo.isProvisional) {314 (0, _utils.assert)(!this._initializedPage);315 let pageOrError;316 try {317 this._setSession(session);318 await Promise.all([this._initializePageProxySession(), this._initializeSession(session, false, ({319 frameTree320 }) => this._handleFrameTree(frameTree))]);321 pageOrError = this._page;322 } catch (e) {323 pageOrError = e;324 }325 if (targetInfo.isPaused) this._pageProxySession.sendMayFail('Target.resume', {326 targetId: targetInfo.targetId327 });328 if (pageOrError instanceof _page.Page && this._page.mainFrame().url() === '') {329 try {330 // Initial empty page has an empty url. We should wait until the first real url has been loaded,331 // even if that url is about:blank. This is especially important for popups, where we need the332 // actual url before interacting with it.333 await this._firstNonInitialNavigationCommittedPromise;334 } catch (e) {335 pageOrError = e;336 }337 } else {338 // Avoid rejection on disconnect.339 this._firstNonInitialNavigationCommittedPromise.catch(() => {});340 }341 await this._page.initOpener(this._opener); // Note: it is important to call |reportAsNew| before resolving pageOrError promise,342 // so that anyone who awaits pageOrError got a ready and reported page.343 this._initializedPage = pageOrError instanceof _page.Page ? pageOrError : null;344 this._page.reportAsNew(pageOrError instanceof _page.Page ? undefined : pageOrError);345 this._pagePromise.resolve(pageOrError);346 } else {347 (0, _utils.assert)(targetInfo.isProvisional);348 (0, _utils.assert)(!this._provisionalPage);349 this._provisionalPage = new _wkProvisionalPage.WKProvisionalPage(session, this);350 if (targetInfo.isPaused) {351 this._provisionalPage.initializationPromise.then(() => {352 this._pageProxySession.sendMayFail('Target.resume', {353 targetId: targetInfo.targetId354 });355 });356 }357 }358 }359 _onDispatchMessageFromTarget(event) {360 const {361 targetId,362 message363 } = event;364 if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) this._provisionalPage._session.dispatchMessage(JSON.parse(message));else if (this._session.sessionId === targetId) this._session.dispatchMessage(JSON.parse(message));else throw new Error('Unknown target: ' + targetId);365 }366 _addSessionListeners() {367 // TODO: remove Page.willRequestOpenWindow and Page.didRequestOpenWindow from the protocol.368 this._sessionListeners = [_eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame, false)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameDetached', event => this._onFrameDetached(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameScheduledNavigation', event => this._onFrameScheduledNavigation(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.loadEventFired', event => this._onLifecycleEvent(event.frameId, 'load')), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.domContentEventFired', event => this._onLifecycleEvent(event.frameId, 'domcontentloaded')), _eventsHelper.eventsHelper.addEventListener(this._session, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Console.messageAdded', event => this._onConsoleMessage(event)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Console.messageRepeatCountUpdated', event => this._onConsoleRepeatCountUpdated(event)), _eventsHelper.eventsHelper.addEventListener(this._pageProxySession, 'Dialog.javascriptDialogOpening', event => this._onDialog(event)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.fileChooserOpened', event => this._onFileChooserOpened(event)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.requestWillBeSent', e => this._onRequestWillBeSent(this._session, e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.requestIntercepted', e => this._onRequestIntercepted(this._session, e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.responseReceived', e => this._onResponseReceived(e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.loadingFinished', e => this._onLoadingFinished(e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.loadingFailed', e => this._onLoadingFailed(e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage))];369 }370 async _updateState(method, params) {371 await this._forAllSessions(session => session.send(method, params).then());372 }373 async _forAllSessions(callback) {374 const sessions = [this._session]; // If the state changes during provisional load, push it to the provisional page375 // as well to always be in sync with the backend.376 if (this._provisionalPage) sessions.push(this._provisionalPage._session);377 await Promise.all(sessions.map(session => callback(session).catch(e => {})));378 }379 _onFrameScheduledNavigation(frameId) {380 this._page._frameManager.frameRequestedNavigation(frameId);381 }382 _onFrameStoppedLoading(frameId) {383 this._page._frameManager.frameStoppedLoading(frameId);384 }385 _onLifecycleEvent(frameId, event) {386 this._page._frameManager.frameLifecycleEvent(frameId, event);387 }388 _handleFrameTree(frameTree) {389 this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);390 this._onFrameNavigated(frameTree.frame, true);391 this._page._frameManager.frameLifecycleEvent(frameTree.frame.id, 'domcontentloaded');392 this._page._frameManager.frameLifecycleEvent(frameTree.frame.id, 'load');393 if (!frameTree.childFrames) return;394 for (const child of frameTree.childFrames) this._handleFrameTree(child);395 }396 _onFrameAttached(frameId, parentFrameId) {397 return this._page._frameManager.frameAttached(frameId, parentFrameId);398 }399 _onFrameNavigated(framePayload, initial) {400 const frame = this._page._frameManager.frame(framePayload.id);401 (0, _utils.assert)(frame);402 this._removeContextsForFrame(frame, true);403 if (!framePayload.parentId) this._workers.clear();404 this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url, framePayload.name || '', framePayload.loaderId, initial);405 if (!initial) this._firstNonInitialNavigationCommittedFulfill();406 }407 _onFrameNavigatedWithinDocument(frameId, url) {408 this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);409 }410 _onFrameDetached(frameId) {411 this._page._frameManager.frameDetached(frameId);412 }413 _removeContextsForFrame(frame, notifyFrame) {414 for (const [contextId, context] of this._contextIdToContext) {415 if (context.frame === frame) {416 this._contextIdToContext.delete(contextId);417 if (notifyFrame) frame._contextDestroyed(context);418 }419 }420 }421 _onExecutionContextCreated(contextPayload) {422 if (this._contextIdToContext.has(contextPayload.id)) return;423 const frame = this._page._frameManager.frame(contextPayload.frameId);424 if (!frame) return;425 const delegate = new _wkExecutionContext.WKExecutionContext(this._session, contextPayload.id);426 let worldName = null;427 if (contextPayload.type === 'normal') worldName = 'main';else if (contextPayload.type === 'user' && contextPayload.name === UTILITY_WORLD_NAME) worldName = 'utility';428 const context = new dom.FrameExecutionContext(delegate, frame, worldName);429 context[contextDelegateSymbol] = delegate;430 if (worldName) frame._contextCreated(worldName, context);431 if (contextPayload.type === 'normal' && frame === this._page.mainFrame()) this._mainFrameContextId = contextPayload.id;432 this._contextIdToContext.set(contextPayload.id, context);433 }434 async navigateFrame(frame, url, referrer) {435 if (this._pageProxySession.isDisposed()) throw new Error('Target closed');436 const pageProxyId = this._pageProxySession.sessionId;437 const result = await this._pageProxySession.connection.browserSession.send('Playwright.navigate', {438 url,439 pageProxyId,440 frameId: frame._id,441 referrer442 });443 return {444 newDocumentId: result.loaderId445 };446 }447 _onConsoleMessage(event) {448 // Note: do no introduce await in this function, otherwise we lose the ordering.449 // For example, frame.setContent relies on this.450 const {451 type,452 level,453 text,454 parameters,455 url,456 line: lineNumber,457 column: columnNumber,458 source459 } = event.message;460 if (level === 'debug' && parameters && parameters[0].value === BINDING_CALL_MESSAGE) {461 const parsedObjectId = JSON.parse(parameters[1].objectId);462 this.pageOrError().then(pageOrError => {463 const context = this._contextIdToContext.get(parsedObjectId.injectedScriptId);464 if (!(pageOrError instanceof Error) && context) this._page._onBindingCalled(parameters[2].value, context);465 });466 return;467 }468 if (level === 'error' && source === 'javascript') {469 const {470 name,471 message472 } = (0, _stackTrace.splitErrorMessage)(text);473 let stack;474 if (event.message.stackTrace) {475 stack = text + '\n' + event.message.stackTrace.map(callFrame => {476 return ` at ${callFrame.functionName || 'unknown'} (${callFrame.url}:${callFrame.lineNumber}:${callFrame.columnNumber})`;477 }).join('\n');478 } else {479 stack = '';480 }481 const error = new Error(message);482 error.stack = stack;483 error.name = name;484 this._page.firePageError(error);485 return;486 }487 let derivedType = type || '';488 if (type === 'log') derivedType = level;else if (type === 'timing') derivedType = 'timeEnd';489 const handles = [];490 for (const p of parameters || []) {491 let context;492 if (p.objectId) {493 const objectId = JSON.parse(p.objectId);494 context = this._contextIdToContext.get(objectId.injectedScriptId);495 } else {496 context = this._contextIdToContext.get(this._mainFrameContextId);497 }498 if (!context) return;499 handles.push(context.createHandle(p));500 }501 this._lastConsoleMessage = {502 derivedType,503 text,504 handles,505 count: 0,506 location: {507 url: url || '',508 lineNumber: (lineNumber || 1) - 1,509 columnNumber: (columnNumber || 1) - 1510 }511 };512 this._onConsoleRepeatCountUpdated({513 count: 1514 });515 }516 _onConsoleRepeatCountUpdated(event) {517 if (this._lastConsoleMessage) {518 const {519 derivedType,520 text,521 handles,522 count,523 location524 } = this._lastConsoleMessage;525 for (let i = count; i < event.count; ++i) this._page._addConsoleMessage(derivedType, handles, location, handles.length ? undefined : text);526 this._lastConsoleMessage.count = event.count;527 }528 }529 _onDialog(event) {530 this._page.emit(_page.Page.Events.Dialog, new dialog.Dialog(this._page, event.type, event.message, async (accept, promptText) => {531 await this._pageProxySession.send('Dialog.handleJavaScriptDialog', {532 accept,533 promptText534 });535 }, event.defaultPrompt));536 }537 async _onFileChooserOpened(event) {538 let handle;539 try {540 const context = await this._page._frameManager.frame(event.frameId)._mainContext();541 handle = context.createHandle(event.element).asElement();542 } catch (e) {543 // During async processing, frame/context may go away. We should not throw.544 return;545 }546 await this._page._onFileChooserOpened(handle);547 }548 static async _setEmulateMedia(session, mediaType, colorScheme, reducedMotion) {549 const promises = [];550 promises.push(session.send('Page.setEmulatedMedia', {551 media: mediaType || ''552 }));553 let appearance = undefined;554 switch (colorScheme) {555 case 'light':556 appearance = 'Light';557 break;558 case 'dark':559 appearance = 'Dark';560 break;561 }562 promises.push(session.send('Page.setForcedAppearance', {563 appearance564 }));565 let reducedMotionWk = undefined;566 switch (reducedMotion) {567 case 'reduce':568 reducedMotionWk = 'Reduce';569 break;570 case 'no-preference':571 reducedMotionWk = 'NoPreference';572 break;573 }574 promises.push(session.send('Page.setForcedReducedMotion', {575 reducedMotion: reducedMotionWk576 }));577 await Promise.all(promises);578 }579 async updateExtraHTTPHeaders() {580 await this._updateState('Network.setExtraHTTPHeaders', {581 headers: (0, _utils.headersArrayToObject)(this._calculateExtraHTTPHeaders(), false582 /* lowerCase */583 )584 });585 }586 _calculateExtraHTTPHeaders() {587 const locale = this._browserContext._options.locale;588 const headers = network.mergeHeaders([this._browserContext._options.extraHTTPHeaders, this._page._state.extraHTTPHeaders, locale ? network.singleHeader('Accept-Language', locale) : undefined]);589 return headers;590 }591 async updateEmulateMedia() {592 const colorScheme = this._page._state.colorScheme;593 const reducedMotion = this._page._state.reducedMotion;594 await this._forAllSessions(session => WKPage._setEmulateMedia(session, this._page._state.mediaType, colorScheme, reducedMotion));595 }596 async setEmulatedSize(emulatedSize) {597 (0, _utils.assert)(this._page._state.emulatedSize === emulatedSize);598 await this._updateViewport();599 }600 async bringToFront() {601 this._pageProxySession.send('Target.activate', {602 targetId: this._session.sessionId603 });604 }605 async _updateViewport() {606 const options = this._browserContext._options;607 const deviceSize = this._page._state.emulatedSize;608 if (deviceSize === null) return;609 const viewportSize = deviceSize.viewport;610 const screenSize = deviceSize.screen;611 const promises = [this._pageProxySession.send('Emulation.setDeviceMetricsOverride', {612 width: viewportSize.width,613 height: viewportSize.height,614 fixedLayout: !!options.isMobile,615 deviceScaleFactor: options.deviceScaleFactor || 1616 }), this._session.send('Page.setScreenSizeOverride', {617 width: screenSize.width,618 height: screenSize.height619 })];620 if (options.isMobile) {621 const angle = viewportSize.width > viewportSize.height ? 90 : 0;622 promises.push(this._session.send('Page.setOrientationOverride', {623 angle624 }));625 }626 await Promise.all(promises);627 }628 async updateRequestInterception() {629 const enabled = this._page._needsRequestInterception();630 await Promise.all([this._updateState('Network.setInterceptionEnabled', {631 enabled632 }), this._updateState('Network.addInterception', {633 url: '.*',634 stage: 'request',635 isRegex: true636 })]);637 }638 async updateOffline() {639 await this._updateState('Network.setEmulateOfflineState', {640 offline: !!this._browserContext._options.offline641 });642 }643 async updateHttpCredentials() {644 const credentials = this._browserContext._options.httpCredentials || {645 username: '',646 password: ''647 };648 await this._pageProxySession.send('Emulation.setAuthCredentials', {649 username: credentials.username,650 password: credentials.password651 });652 }653 async setFileChooserIntercepted(enabled) {654 await this._session.send('Page.setInterceptFileChooserDialog', {655 enabled656 }).catch(e => {}); // target can be closed.657 }658 async reload() {659 await this._session.send('Page.reload');660 }661 goBack() {662 return this._session.send('Page.goBack').then(() => true).catch(error => {663 if (error instanceof Error && error.message.includes(`Protocol error (Page.goBack): Failed to go`)) return false;664 throw error;665 });666 }667 goForward() {668 return this._session.send('Page.goForward').then(() => true).catch(error => {669 if (error instanceof Error && error.message.includes(`Protocol error (Page.goForward): Failed to go`)) return false;670 throw error;671 });672 }673 async exposeBinding(binding) {674 await this._updateBootstrapScript();675 await this._evaluateBindingScript(binding);676 }677 async _evaluateBindingScript(binding) {678 const script = this._bindingToScript(binding);679 await Promise.all(this._page.frames().map(frame => frame.evaluateExpression(script, false, {}).catch(e => {})));680 }681 async evaluateOnNewDocument(script) {682 await this._updateBootstrapScript();683 }684 _bindingToScript(binding) {685 return `self.${binding.name} = (param) => console.debug('${BINDING_CALL_MESSAGE}', {}, param); ${binding.source}`;686 }687 _calculateBootstrapScript() {688 const scripts = [];689 if (!this._page.context()._options.isMobile) {690 scripts.push('delete window.orientation');691 scripts.push('delete window.ondevicemotion');692 scripts.push('delete window.ondeviceorientation');693 }694 for (const binding of this._page.allBindings()) scripts.push(this._bindingToScript(binding));695 scripts.push(...this._browserContext._evaluateOnNewDocumentSources);696 scripts.push(...this._page._evaluateOnNewDocumentSources);697 return scripts.join(';');698 }699 async _updateBootstrapScript() {700 await this._updateState('Page.setBootstrapScript', {701 source: this._calculateBootstrapScript()702 });703 }704 async closePage(runBeforeUnload) {705 await this._stopVideo();706 await this._pageProxySession.sendMayFail('Target.close', {707 targetId: this._session.sessionId,708 runBeforeUnload709 });710 }711 async setBackgroundColor(color) {712 await this._session.send('Page.setDefaultBackgroundColorOverride', {713 color714 });715 }716 _toolbarHeight() {717 var _this$_page$_browserC;718 if ((_this$_page$_browserC = this._page._browserContext._browser) !== null && _this$_page$_browserC !== void 0 && _this$_page$_browserC.options.headful) return _utils.hostPlatform === 'mac10.15' ? 55 : 59;719 return 0;720 }721 async _startVideo(options) {722 (0, _utils.assert)(!this._recordingVideoFile);723 const {724 screencastId725 } = await this._pageProxySession.send('Screencast.startVideo', {726 file: options.outputFile,727 width: options.width,728 height: options.height,729 toolbarHeight: this._toolbarHeight()730 });731 this._recordingVideoFile = options.outputFile;732 this._browserContext._browser._videoStarted(this._browserContext, screencastId, options.outputFile, this.pageOrError());733 }734 async _stopVideo() {735 if (!this._recordingVideoFile) return;736 await this._pageProxySession.sendMayFail('Screencast.stopVideo');737 this._recordingVideoFile = null;738 }739 async takeScreenshot(progress, format, documentRect, viewportRect, quality) {740 const rect = documentRect || viewportRect;741 const result = await this._session.send('Page.snapshotRect', { ...rect,742 coordinateSystem: documentRect ? 'Page' : 'Viewport'743 });744 const prefix = 'data:image/png;base64,';745 let buffer = Buffer.from(result.dataURL.substr(prefix.length), 'base64');746 if (format === 'jpeg') buffer = jpeg.encode(png.PNG.sync.read(buffer), quality).data;747 return buffer;748 }749 async getContentFrame(handle) {750 const nodeInfo = await this._session.send('DOM.describeNode', {751 objectId: handle._objectId752 });753 if (!nodeInfo.contentFrameId) return null;754 return this._page._frameManager.frame(nodeInfo.contentFrameId);755 }756 async getOwnerFrame(handle) {757 if (!handle._objectId) return null;758 const nodeInfo = await this._session.send('DOM.describeNode', {759 objectId: handle._objectId760 });761 return nodeInfo.ownerFrameId || null;762 }763 isElementHandle(remoteObject) {764 return remoteObject.subtype === 'node';765 }766 async getBoundingBox(handle) {767 const quads = await this.getContentQuads(handle);768 if (!quads || !quads.length) return null;769 let minX = Infinity;770 let maxX = -Infinity;771 let minY = Infinity;772 let maxY = -Infinity;773 for (const quad of quads) {774 for (const point of quad) {775 minX = Math.min(minX, point.x);776 maxX = Math.max(maxX, point.x);777 minY = Math.min(minY, point.y);778 maxY = Math.max(maxY, point.y);779 }780 }781 return {782 x: minX,783 y: minY,784 width: maxX - minX,785 height: maxY - minY786 };787 }788 async scrollRectIntoViewIfNeeded(handle, rect) {789 return await this._session.send('DOM.scrollIntoViewIfNeeded', {790 objectId: handle._objectId,791 rect792 }).then(() => 'done').catch(e => {793 if (e instanceof Error && e.message.includes('Node does not have a layout object')) return 'error:notvisible';794 if (e instanceof Error && e.message.includes('Node is detached from document')) return 'error:notconnected';795 throw e;796 });797 }798 async setScreencastOptions(options) {799 if (options) {800 const so = { ...options,801 toolbarHeight: this._toolbarHeight()802 };803 const {804 generation805 } = await this._pageProxySession.send('Screencast.startScreencast', so);806 this._screencastGeneration = generation;807 } else {808 await this._pageProxySession.send('Screencast.stopScreencast');809 }810 }811 _onScreencastFrame(event) {812 const generation = this._screencastGeneration;813 this._page.throttleScreencastFrameAck(() => {814 this._pageProxySession.send('Screencast.screencastFrameAck', {815 generation816 }).catch(e => _debugLogger.debugLogger.log('error', e));817 });818 const buffer = Buffer.from(event.data, 'base64');819 this._page.emit(_page.Page.Events.ScreencastFrame, {820 buffer,821 width: event.deviceWidth,822 height: event.deviceHeight823 });824 }825 rafCountForStablePosition() {826 return process.platform === 'win32' ? 5 : 1;827 }828 async getContentQuads(handle) {829 const result = await this._session.sendMayFail('DOM.getContentQuads', {830 objectId: handle._objectId831 });832 if (!result) return null;833 return result.quads.map(quad => [{834 x: quad[0],835 y: quad[1]836 }, {837 x: quad[2],838 y: quad[3]839 }, {840 x: quad[4],841 y: quad[5]842 }, {843 x: quad[6],844 y: quad[7]845 }]);846 }847 async setInputFiles(handle, files) {848 const objectId = handle._objectId;849 const protocolFiles = files.map(file => ({850 name: file.name,851 type: file.mimeType,852 data: file.buffer853 }));854 await this._session.send('DOM.setInputFiles', {855 objectId,856 files: protocolFiles857 });858 }859 async adoptElementHandle(handle, to) {860 const result = await this._session.sendMayFail('DOM.resolveNode', {861 objectId: handle._objectId,862 executionContextId: to[contextDelegateSymbol]._contextId863 });864 if (!result || result.object.subtype === 'null') throw new Error(dom.kUnableToAdoptErrorMessage);865 return to.createHandle(result.object);866 }867 async getAccessibilityTree(needle) {868 return (0, _wkAccessibility.getAccessibilityTree)(this._session, needle);869 }870 async inputActionEpilogue() {}871 async getFrameElement(frame) {872 const parent = frame.parentFrame();873 if (!parent) throw new Error('Frame has been detached.');874 const info = this._page.parseSelector('frame,iframe');875 const handles = await this._page.selectors._queryAll(parent, info);876 const items = await Promise.all(handles.map(async handle => {877 const frame = await handle.contentFrame().catch(e => null);878 return {879 handle,880 frame881 };882 }));883 const result = items.find(item => item.frame === frame);884 items.map(item => item === result ? Promise.resolve() : item.handle.dispose());885 if (!result) throw new Error('Frame has been detached.');886 return result.handle;887 }888 _onRequestWillBeSent(session, event) {889 if (event.request.url.startsWith('data:')) return;890 let redirectedFrom = null;891 if (event.redirectResponse) {892 const request = this._requestIdToRequest.get(event.requestId); // If we connect late to the target, we could have missed the requestWillBeSent event.893 if (request) {894 this._handleRequestRedirect(request, event.redirectResponse, event.timestamp);895 redirectedFrom = request;896 }897 }898 const frame = redirectedFrom ? redirectedFrom.request.frame() : this._page._frameManager.frame(event.frameId); // sometimes we get stray network events for detached frames899 // TODO(einbinder) why?900 if (!frame) return; // TODO(einbinder) this will fail if we are an XHR document request901 const isNavigationRequest = event.type === 'Document';902 const documentId = isNavigationRequest ? event.loaderId : undefined;903 let route = null; // We do not support intercepting redirects.904 if (this._page._needsRequestInterception() && !redirectedFrom) route = new _wkInterceptableRequest.WKRouteImpl(session, event.requestId);905 const request = new _wkInterceptableRequest.WKInterceptableRequest(session, route, frame, event, redirectedFrom, documentId);906 this._requestIdToRequest.set(event.requestId, request);907 this._page._frameManager.requestStarted(request.request, route || undefined);908 }909 _handleRequestRedirect(request, responsePayload, timestamp) {910 const response = request.createResponse(responsePayload);911 response._securityDetailsFinished();912 response._serverAddrFinished();913 response._requestFinished(responsePayload.timing ? _helper.helper.secondsToRoundishMillis(timestamp - request._timestamp) : -1);914 this._requestIdToRequest.delete(request._requestId);915 this._page._frameManager.requestReceivedResponse(response);916 this._page._frameManager.reportRequestFinished(request.request, response);917 }918 _onRequestIntercepted(session, event) {919 const request = this._requestIdToRequest.get(event.requestId);920 if (!request) {921 session.sendMayFail('Network.interceptRequestWithError', {922 errorType: 'Cancellation',923 requestId: event.requestId924 });925 return;926 }927 if (!request._route) {928 // Intercepted, although we do not intend to allow interception.929 // Just continue.930 session.sendMayFail('Network.interceptWithRequest', {931 requestId: request._requestId932 });933 } else {934 request._route._requestInterceptedPromise.resolve();935 }936 }937 _onResponseReceived(event) {938 const request = this._requestIdToRequest.get(event.requestId); // FileUpload sends a response without a matching request.939 if (!request) return;940 this._requestIdToResponseReceivedPayloadEvent.set(request._requestId, event);941 const response = request.createResponse(event.response);942 if (event.response.requestHeaders && Object.keys(event.response.requestHeaders).length) {943 const headers = { ...event.response.requestHeaders944 };945 if (!headers['host']) headers['Host'] = new URL(request.request.url()).host;946 request.request.setRawRequestHeaders((0, _utils.headersObjectToArray)(headers));947 }948 this._page._frameManager.requestReceivedResponse(response);949 if (response.status() === 204) {950 this._onLoadingFailed({951 requestId: event.requestId,952 errorText: 'Aborted: 204 No Content',953 timestamp: event.timestamp954 });955 }956 }957 _onLoadingFinished(event) {958 const request = this._requestIdToRequest.get(event.requestId); // For certain requestIds we never receive requestWillBeSent event.959 // @see https://crbug.com/750469960 if (!request) return; // Under certain conditions we never get the Network.responseReceived961 // event from protocol. @see https://crbug.com/883475962 const response = request.request._existingResponse();963 if (response) {964 var _event$metrics, _event$metrics2, _event$metrics2$secur, _responseReceivedPayl, _responseReceivedPayl2, _responseReceivedPayl3, _responseReceivedPayl4, _responseReceivedPayl5, _responseReceivedPayl6, _event$metrics3, _event$metrics4, _event$metrics5;965 const responseReceivedPayload = this._requestIdToResponseReceivedPayloadEvent.get(request._requestId);966 response._serverAddrFinished(parseRemoteAddress(event === null || event === void 0 ? void 0 : (_event$metrics = event.metrics) === null || _event$metrics === void 0 ? void 0 : _event$metrics.remoteAddress));967 response._securityDetailsFinished({968 protocol: isLoadedSecurely(response.url(), response.timing()) ? (_event$metrics2 = event.metrics) === null || _event$metrics2 === void 0 ? void 0 : (_event$metrics2$secur = _event$metrics2.securityConnection) === null || _event$metrics2$secur === void 0 ? void 0 : _event$metrics2$secur.protocol : undefined,969 subjectName: responseReceivedPayload === null || responseReceivedPayload === void 0 ? void 0 : (_responseReceivedPayl = responseReceivedPayload.response.security) === null || _responseReceivedPayl === void 0 ? void 0 : (_responseReceivedPayl2 = _responseReceivedPayl.certificate) === null || _responseReceivedPayl2 === void 0 ? void 0 : _responseReceivedPayl2.subject,970 validFrom: responseReceivedPayload === null || responseReceivedPayload === void 0 ? void 0 : (_responseReceivedPayl3 = responseReceivedPayload.response.security) === null || _responseReceivedPayl3 === void 0 ? void 0 : (_responseReceivedPayl4 = _responseReceivedPayl3.certificate) === null || _responseReceivedPayl4 === void 0 ? void 0 : _responseReceivedPayl4.validFrom,971 validTo: responseReceivedPayload === null || responseReceivedPayload === void 0 ? void 0 : (_responseReceivedPayl5 = responseReceivedPayload.response.security) === null || _responseReceivedPayl5 === void 0 ? void 0 : (_responseReceivedPayl6 = _responseReceivedPayl5.certificate) === null || _responseReceivedPayl6 === void 0 ? void 0 : _responseReceivedPayl6.validUntil972 });973 if ((_event$metrics3 = event.metrics) !== null && _event$metrics3 !== void 0 && _event$metrics3.protocol) response._setHttpVersion(event.metrics.protocol);974 if ((_event$metrics4 = event.metrics) !== null && _event$metrics4 !== void 0 && _event$metrics4.responseBodyBytesReceived) request.request.responseSize.encodedBodySize = event.metrics.responseBodyBytesReceived;975 if ((_event$metrics5 = event.metrics) !== null && _event$metrics5 !== void 0 && _event$metrics5.responseHeaderBytesReceived) request.request.responseSize.responseHeadersSize = event.metrics.responseHeaderBytesReceived;976 response._requestFinished(_helper.helper.secondsToRoundishMillis(event.timestamp - request._timestamp));977 }978 this._requestIdToResponseReceivedPayloadEvent.delete(request._requestId);979 this._requestIdToRequest.delete(request._requestId);980 this._page._frameManager.reportRequestFinished(request.request, response);981 }982 _onLoadingFailed(event) {983 const request = this._requestIdToRequest.get(event.requestId); // For certain requestIds we never receive requestWillBeSent event.984 // @see https://crbug.com/750469985 if (!request) return;986 const response = request.request._existingResponse();987 if (response) {988 response._serverAddrFinished();989 response._securityDetailsFinished();990 response._requestFinished(_helper.helper.secondsToRoundishMillis(event.timestamp - request._timestamp));991 }992 this._requestIdToRequest.delete(request._requestId);993 request.request._setFailureText(event.errorText);994 this._page._frameManager.requestFailed(request.request, event.errorText.includes('cancelled'));995 }996 async _grantPermissions(origin, permissions) {997 const webPermissionToProtocol = new Map([['geolocation', 'geolocation']]);998 const filtered = permissions.map(permission => {999 const protocolPermission = webPermissionToProtocol.get(permission);1000 if (!protocolPermission) throw new Error('Unknown permission: ' + permission);1001 return protocolPermission;1002 });1003 await this._pageProxySession.send('Emulation.grantPermissions', {1004 origin,1005 permissions: filtered1006 });1007 }1008 async _clearPermissions() {1009 await this._pageProxySession.send('Emulation.resetPermissions', {});1010 }...

Full Screen

Full Screen

wkBrowser.js

Source:wkBrowser.js Github

copy

Full Screen

...237 browserContextId: this._browserContextId238 });239 }240 async _doGrantPermissions(origin, permissions) {241 await Promise.all(this.pages().map(page => page._delegate._grantPermissions(origin, permissions)));242 }243 async _doClearPermissions() {244 await Promise.all(this.pages().map(page => page._delegate._clearPermissions()));245 }246 async setGeolocation(geolocation) {247 (0, _browserContext.verifyGeolocation)(geolocation);248 this._options.geolocation = geolocation;249 const payload = geolocation ? { ...geolocation,250 timestamp: Date.now()251 } : undefined;252 await this._browser._browserSession.send('Playwright.setGeolocationOverride', {253 browserContextId: this._browserContextId,254 geolocation: payload255 });...

Full Screen

Full Screen

deployer.js

Source:deployer.js Github

copy

Full Screen

...122 const { appId, currentTimestamp } = { ...DEFAULT_DISPUTABLE_INITIALIZATION_PARAMS, ...options }123 const receipt = await this.dao.newAppInstance(appId, this.baseDisputable.address, '0x', false, { from: owner })124 const disputable = await this.baseDisputable.constructor.at(getInstalledApp(receipt, appId))125 await this.acl.createPermission(this.agreement.address, disputable.address, SET_AGREEMENT_ROLE, owner, { from: owner })126 await this._grantPermissions(disputable, SUBMIT_ROLE, options.submitters, owner)127 await this._grantPermissions(disputable, CHALLENGE_ROLE, options.challengers, owner)128 if (!options.collateralToken && !this.collateralToken) await this.deployCollateralToken(options)129 await disputable.initialize()130 if (options.activate || options.activate === undefined) {131 const collateralToken = options.collateralToken || this.collateralToken132 const { actionCollateral, challengeCollateral, challengeDuration } = { ...DEFAULT_DISPUTABLE_INITIALIZATION_PARAMS, ...options }133 await this.agreement.activate(disputable.address, collateralToken.address, challengeDuration, actionCollateral, challengeCollateral, { from: owner })134 }135 if (currentTimestamp) await this.mockTime(disputable, currentTimestamp)136 this.previousDeploy = { ...this.previousDeploy, disputable }137 return disputable138 }139 async deployArbitrator(options = {}) {140 let { feeToken, feeAmount } = { ...DEFAULT_AGREEMENT_INITIALIZATION_PARAMS.arbitrator, ...options }141 if (!feeToken.address) feeToken = await this.deployToken(feeToken)142 const Arbitrator = this._getContract('ArbitratorMock')143 const arbitrator = await Arbitrator.new(feeToken.address, feeAmount)144 this.previousDeploy = { ...this.previousDeploy, arbitrator }145 return arbitrator146 }147 async deployStakingFactory() {148 const StakingFactory = this._getContract('StakingFactory')149 const stakingFactory = await StakingFactory.new()150 this.previousDeploy = { ...this.previousDeploy, stakingFactory }151 return stakingFactory152 }153 async deployCollateralToken(options = {}) {154 const collateralToken = await this.deployToken(options)155 this.previousDeploy = { ...this.previousDeploy, collateralToken }156 return collateralToken157 }158 async deployBase() {159 const Agreement = this._getContract('AgreementMock')160 const base = await Agreement.new()161 this.previousDeploy = { ...this.previousDeploy, base }162 return base163 }164 async deployBaseDisputable() {165 const Disputable = this._getContract('DisputableAppMock')166 const baseDisputable = await Disputable.new()167 this.previousDeploy = { ...this.previousDeploy, baseDisputable }168 return baseDisputable169 }170 async deployDAO(owner) {171 const Kernel = this._getContract('Kernel')172 const kernelBase = await Kernel.new(true)173 const ACL = this._getContract('ACL')174 const aclBase = await ACL.new()175 const EVMScriptRegistryFactory = this._getContract('EVMScriptRegistryFactory')176 const regFact = await EVMScriptRegistryFactory.new()177 const DAOFactory = this._getContract('DAOFactory')178 const daoFact = await DAOFactory.new(kernelBase.address, aclBase.address, regFact.address)179 const kernelReceipt = await daoFact.newDAO(owner)180 const dao = await Kernel.at(getEventArgument(kernelReceipt, 'DeployDAO', 'dao'))181 const acl = await ACL.at(await dao.acl())182 const APP_MANAGER_ROLE = await kernelBase.APP_MANAGER_ROLE()183 await acl.createPermission(owner, dao.address, APP_MANAGER_ROLE, owner, { from: owner })184 this.previousDeploy = { ...this.previousDeploy, dao, acl, owner }185 return dao186 }187 async deployToken({ name = 'My Sample Token', decimals = 18, symbol = 'MST' }) {188 const MiniMeToken = this._getContract('MiniMeToken')189 return MiniMeToken.new(ZERO_ADDRESS, ZERO_ADDRESS, 0, name, decimals, symbol, true)190 }191 async mockTime(timeMockable, timestamp) {192 if (!this.clockMock) await this.deployClockMock()193 await timeMockable.setClock(this.clockMock.address)194 return this.clockMock.mockSetTimestamp(timestamp)195 }196 async deployClockMock() {197 const ClockMock = this._getContract('TimeHelpersMock')198 const clockMock = await ClockMock.new()199 this.previousDeploy = { ...this.previousDeploy, clockMock }200 return clockMock201 }202 async _createPermissions(app, permissions, to, manager = to) {203 for (const permission of permissions) {204 const ROLE = await app[permission]()205 await this.acl.createPermission(to, app.address, ROLE, manager, { from: manager })206 }207 }208 async _grantPermissions(app, permission, users, manager) {209 if (!users) users = [ANY_ENTITY]210 for (const user of users) {211 if (users.indexOf(user) === 0) await this.acl.createPermission(user, app.address, permission, manager, { from: manager })212 else await this.acl.grantPermission(user, app.address, permission, { from: manager })213 }214 }215 _getContract(name) {216 return this.artifacts.require(name)217 }218 async _getSender() {219 if (!this.sender) {220 const accounts = await this.web3.eth.getAccounts()221 this.sender = accounts[0]222 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { webkit } = require('playwright');2(async () => {3 const browser = await webkit.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await context._grantPermissions(['geolocation']);7 await page.waitForTimeout(5000);8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _grantPermissions } = require('playwright/lib/server/browserContext');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 await _grantPermissions(context, ['geolocation']);7 const page = await context.newPage();8 await page.click('text="Your location"');9 await page.waitForTimeout(5000);10 await page.close();11 await context.close();12 await browser.close();13})();14[0224/102717.665:ERROR:device_event_log_impl.cc(208)] [10:27:17.665] USB: usb_device_handle_win.cc:1040 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)15[0224/102717.668:ERROR:device_event_log_impl.cc(208)] [10:27:17.668] USB: usb_device_handle_win.cc:1040 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)16[0224/102717.670:ERROR:device_event_log_impl.cc(208)] [10:27:17.670] USB: usb_device_handle_win.cc:1040 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)17[0224/102717.673:ERROR:device_event_log_impl.cc(208)] [10:27:17.673] USB: usb_device_handle_win.cc:1040 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)18[0224/102717.675:ERROR:device_event_log_impl.cc(208)] [10:27:17.675] USB: usb_device_handle_win.cc:1040 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)19[0224/102717.678:ERROR:device_event_log_impl.cc(208)] [10:27:17.678] USB: usb_device_handle_win.cc:1040 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 await browser._grantPermissions(['geolocation']);5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('text=Share Location');8 await page.click('text=Always share');9 await page.waitForSelector('text=You are here');10 await browser.close();11})();12{13 "scripts": {14 },15 "dependencies": {16 }17}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { _grantPermissions } = require('playwright/lib/server/chromium/crBrowser');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await _grantPermissions(page, ['geolocation']);8 await page.click('text=Try it');9 await page.waitForSelector('text=Latitude:');10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext({16 geolocation: { longitude: 12.492507, latitude: 41.889938 },17 });18 const page = await context.newPage();19 await page.click('text=Try it');20 await page.waitForSelector('text=Latitude:');21 await browser.close();22})();23const { chromium } = require('playwright');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 await page.click('text=Try it');29 await page.waitForSelector('text=Latitude:');30 const latitude = await page.$eval('text=Latitude:', (el) => el.textContent);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _grantPermissions } = require('playwright/lib/server/browserContext.js');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 await _grantPermissions(context, ['geolocation']);7 const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _grantPermissions } = require('playwright');2await _grantPermissions(['geolocation']);3const { _grantPermissions } = require('playwright');4await _grantPermissions(['geolocation']);5const { _grantPermissions } = require('playwright');6await _grantPermissions(['geolocation']);7const { _grantPermissions } = require('playwright');8await _grantPermissions(['geolocation']);9const { _grantPermissions } = require('playwright');10await _grantPermissions(['geolocation']);11const { _grantPermissions } = require('playwright');12await _grantPermissions(['geolocation']);13const { _grantPermissions } = require('playwright');14await _grantPermissions(['geolocation']);15const { _grantPermissions } = require('playwright');16await _grantPermissions(['geolocation']);17const { _grantPermissions } = require('playwright');18await _grantPermissions(['geolocation']);19const { _grantPermissions } = require('playwright');20await _grantPermissions(['geolocation']);21const { _grantPermissions } = require('playwright');22await _grantPermissions(['geolocation']);23const { _grantPermissions } = require('playwright');24await _grantPermissions(['geolocation']);25const { _grantPermissions } = require('playwright');26await _grantPermissions(['geolocation']);27const { _grantPermissions } = require('playwright');28await _grantPermissions(['geolocation']);29const { _grantPermissions } = require('playwright');30await _grantPermissions(['geolocation']);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _grantPermissions } = require('playwright/lib/server/chromium/crBrowser');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await _grantPermissions(page, ['geolocation']);7})();8const { _grantPermissions } = require('playwright/lib/server/chromium/crBrowser');9(async () => {10 const browser = await chromium.launch();11 const context = await browser.newContext();12 const page = await context.newPage();13 await _grantPermissions(page, ['geolocation']);14})();15const { _grantPermissions } = require('playwright/lib/server/chromium/crBrowser');16(async () => {17 const browser = await chromium.launch();18 const context = await browser.newContext();19 const page = await context.newPage();20 await _grantPermissions(page, ['geolocation']);21})();22const { _grantPermissions } = require('playwright/lib/server/chromium/crBrowser');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await _grantPermissions(page, ['geolocation']);28})();29const { _grantPermissions } = require('playwright/lib/server/chromium/crBrowser');30(async () => {31 const browser = await chromium.launch();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _grantPermissions } = require('playwright/lib/server/chromium/crBrowser');2(async () => {3 const browser = await chromium.launch({4 '--use-file-for-fake-video-capture=' + path.join(__dirname, 'test.webm')5 });6 const context = await browser.newContext();7 const page = await context.newPage();8 await _grantPermissions(page, ['camera', 'microphone']);9 await page.click('text=Start Recording');10})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _grantPermissions } = require('@playwright/test/lib/server/browserContext');2const { chromium, webkit, firefox } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 await _grantPermissions(context, ['geolocation']);7 const page = await context.newPage();8 await page.click('text=Ask');9 await page.waitForTimeout(5000);10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { InternalAPI } = require('playwright-core/lib/client/api');2const { chromium } = require('playwright-core');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await InternalAPI.grantPermissions(page, ['geolocation']);7 await page.reload();8 await page.waitForTimeout(10000);9 await browser.close();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