Best JavaScript code snippet using playwright-internal
crPage.js
Source:crPage.js
...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) {659 if (!this._page._frameManager.frame(this._targetId)) return; // Our frame/subtree may be gone already.660 this._page.emit(_page.Page.Events.Dialog, new dialog.Dialog(this._page, event.type, event.message, async (accept, promptText) => {661 await this._client.send('Page.handleJavaScriptDialog', {662 accept,663 promptText664 });665 }, event.defaultPrompt));666 }667 _handleException(exceptionDetails) {668 this._page.firePageError((0, _crProtocolHelper.exceptionToError)(exceptionDetails));669 }670 async _onTargetCrashed() {671 this._client._markAsCrashed();672 this._page._didCrash();673 }674 _onLogEntryAdded(event) {675 const {676 level,677 text,678 args,679 source,680 url,681 lineNumber682 } = event.entry;683 if (args) args.map(arg => (0, _crProtocolHelper.releaseObject)(this._client, arg.objectId));684 if (source !== 'worker') {685 const location = {686 url: url || '',687 lineNumber: lineNumber || 0,688 columnNumber: 0689 };690 this._page._addConsoleMessage(level, [], location, text);691 }692 }693 async _onFileChooserOpened(event) {694 const frame = this._page._frameManager.frame(event.frameId);695 if (!frame) return;696 let handle;697 try {698 const utilityContext = await frame._utilityContext();699 handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);700 } catch (e) {701 // During async processing, frame/context may go away. We should not throw.702 return;703 }704 await this._page._onFileChooserOpened(handle);705 }706 _willBeginDownload() {707 const originPage = this._crPage._initializedPage;708 if (!originPage) {709 // Resume the page creation with an error. The page will automatically close right710 // after the download begins.711 this._firstNonInitialNavigationCommittedReject(new Error('Starting new page download'));712 }713 }714 _onScreencastFrame(payload) {715 this._page.throttleScreencastFrameAck(() => {716 this._client.send('Page.screencastFrameAck', {717 sessionId: payload.sessionId718 }).catch(() => {});719 });720 const buffer = Buffer.from(payload.data, 'base64');721 this._page.emit(_page.Page.Events.ScreencastFrame, {722 buffer,723 timestamp: payload.metadata.timestamp,724 width: payload.metadata.deviceWidth,725 height: payload.metadata.deviceHeight726 });727 }728 async _createVideoRecorder(screencastId, options) {729 (0, _utils.assert)(!this._screencastId);730 const ffmpegPath = _registry.registry.findExecutable('ffmpeg').executablePathOrDie(this._page._browserContext._browser.options.sdkLanguage);731 this._videoRecorder = await _videoRecorder.VideoRecorder.launch(this._crPage._page, ffmpegPath, options);732 this._screencastId = screencastId;733 }734 async _startVideoRecording(options) {735 const screencastId = this._screencastId;736 (0, _utils.assert)(screencastId);737 this._page.once(_page.Page.Events.Close, () => this._stopVideoRecording().catch(() => {}));738 const gotFirstFrame = new Promise(f => this._client.once('Page.screencastFrame', f));739 await this._startScreencast(this._videoRecorder, {740 format: 'jpeg',741 quality: 90,742 maxWidth: options.width,743 maxHeight: options.height744 }); // Wait for the first frame before reporting video to the client.745 gotFirstFrame.then(() => {746 this._crPage._browserContext._browser._videoStarted(this._crPage._browserContext, screencastId, options.outputFile, this._crPage.pageOrError());747 });748 }749 async _stopVideoRecording() {750 if (!this._screencastId) return;751 const screencastId = this._screencastId;752 this._screencastId = null;753 const recorder = this._videoRecorder;754 this._videoRecorder = null;755 await this._stopScreencast(recorder);756 await recorder.stop().catch(() => {}); // Keep the video artifact in the map utntil encoding is fully finished, if the context757 // starts closing before the video is fully written to disk it will wait for it.758 const video = this._crPage._browserContext._browser._takeVideo(screencastId);759 video === null || video === void 0 ? void 0 : video.reportFinished();760 }761 async _startScreencast(client, options = {}) {762 this._screencastClients.add(client);763 if (this._screencastClients.size === 1) await this._client.send('Page.startScreencast', options);764 }765 async _stopScreencast(client) {766 this._screencastClients.delete(client);767 if (!this._screencastClients.size) await this._client._sendMayFail('Page.stopScreencast');768 }769 async _updateExtraHTTPHeaders(initial) {770 const headers = network.mergeHeaders([this._crPage._browserContext._options.extraHTTPHeaders, this._page._state.extraHTTPHeaders]);771 if (!initial || headers.length) await this._client.send('Network.setExtraHTTPHeaders', {772 headers: (0, _utils.headersArrayToObject)(headers, false773 /* lowerCase */774 )775 });776 }777 async _updateGeolocation(initial) {778 const geolocation = this._crPage._browserContext._options.geolocation;779 if (!initial || geolocation) await this._client.send('Emulation.setGeolocationOverride', geolocation || {});780 }781 async _updateOffline(initial) {782 const offline = !!this._crPage._browserContext._options.offline;783 if (!initial || offline) await this._networkManager.setOffline(offline);784 }785 async _updateHttpCredentials(initial) {786 const credentials = this._crPage._browserContext._options.httpCredentials || null;787 if (!initial || credentials) await this._networkManager.authenticate(credentials);788 }789 async _updateViewport() {790 if (this._crPage._browserContext._browser.isClank()) return;791 (0, _utils.assert)(this._isMainFrame());...
map.directives.js
Source:map.directives.js
1'use strict';2angular.module('app.common.map.directives', [])3 .directive('eventBroadcast', function (MapState) {4 // Extend leaflet directive to register baselayer change event globally5 return {6 restrict: "A",7 priority: 1,8 scope: false,9 replace: false,10 require: 'leaflet',11 link: function link(scope, element, attrs, controller) {12 controller.getMap().then(function (map) {13 map.on('baselayerchange', function (leafletEvent) {14 MapState.setSelectedLayerName(leafletEvent.name);15 });16 map.on('overlayadd', function (leafletEvent) {17 MapState.setOverlayEnabled(leafletEvent.name);18 });19 map.on('overlayremove', function (leafletEvent) {20 MapState.setOverlayDisabled(leafletEvent.name);21 });22 map.on('unload', function () {23 map.off('overlayadd overlayremove baselayerchange');24 });25 });26 }27 };28 })29 .directive('leafletVectorLayer', function ($parse, leafletBoundsHelpers) {30 return {31 require: '^leaflet',32 restrict: 'A',33 scope: false,34 replace: false,35 link: function ($scope, element, attrs, leafletCtrl) {36 var vectorLayerAttr = $parse(attrs.leafletVectorLayer);37 var leafletVectorGrid = null;38 leafletCtrl.getMap().then(function (map) {39 $scope.$watch(vectorLayerAttr, function (props) {40 if (leafletVectorGrid) {41 map.removeLayer(leafletVectorGrid);42 leafletVectorGrid = null;43 }44 if (props && props.url) {45 leafletVectorGrid = createVectorLayer(props.url, props.bounds).addTo(map);46 }47 });48 });49 function createVectorLayer(url, bounds) {50 return L.vectorGrid.protobuf(url, {51 minZoom: 6,52 pane: 'overlayPane',53 rendererFactory: L.canvas.tile,54 fetchOptions: {55 credentials: 'include'56 },57 bounds: bounds ? leafletBoundsHelpers.createLeafletBounds(bounds) : null,58 vectorTileLayerStyles: {59 all: {60 fill: true,61 fillColor: 'green',62 fillOpacity: 0.25,63 weight: 1,64 color: 'black'65 }66 }67 });68 }69 }70 };71 })72 .component('rHuntingAreaAsVectorLayer', {73 template: '<div leaflet-vector-layer="$ctrl.vectorLayer"></div>',74 require: {75 leaflet: '^^leaflet'76 },77 bindings: {78 area: '<'79 },80 controller: function () {81 var $ctrl = this;82 $ctrl.$onInit = function () {83 if ($ctrl.area && $ctrl.area.bounds && $ctrl.area.areaId) {84 var bounds = $ctrl.area.bounds;85 var vectorLayerTemplate = _.template('/api/v1/vector/hunting-club-area/<%= id %>/{z}/{x}/{y}');86 $ctrl.vectorLayer = {87 url: vectorLayerTemplate({id: $ctrl.area.areaId}),88 bounds: {89 southWest: {lat: bounds.minLat, lng: bounds.minLng},90 northEast: {lat: bounds.maxLat, lng: bounds.maxLng}91 }92 };93 } else {94 $ctrl.vectorLayer = null;95 }96 };97 }98 })99 .directive('rGeolocationKeepMarkerCenter', function (MapUtil) {100 return {101 scope: false,102 replace: false,103 require: ['rGeolocationMarker', 'rGeolocationCenter'],104 link: function (scope, element, attrs, ctrls) {105 var markerController = ctrls[0];106 var centerController = ctrls[1];107 scope.rGeolocationKeepMarkerCenterValue = markerController.getLocation();108 scope.$watch('rGeolocationKeepMarkerCenterValue', function (geoLocation) {109 if (MapUtil.isValidGeoLocation(geoLocation)) {110 centerController.updateCenter(geoLocation);111 }112 }, true);113 }114 };115 })116 .directive('rGeolocationCenter',117 function ($timeout, $parse, leafletHelpers, leafletMapEvents, MapUtil, MapState, WGS84) {118 function geoLocationToLatLng(geoLocation, currentZoom) {119 var latlng = WGS84.fromETRS(geoLocation.latitude, geoLocation.longitude);120 latlng.zoom = MapUtil.limitDefaultZoom(geoLocation.zoom || currentZoom);121 return latlng;122 }123 return {124 restrict: 'A',125 require: ['rGeolocationCenter', 'leaflet'],126 scope: false,127 replace: false,128 controller: function () {129 var $ctrl = this;130 $ctrl.updateCenter = function (geoLocation, zoom) {131 if (!MapUtil.isValidGeoLocation(geoLocation)) {132 return;133 }134 var actualZoom = zoom || MapState.getZoom() || $ctrl.map.getZoom();135 $ctrl.updateLatLng(geoLocationToLatLng(geoLocation, actualZoom));136 };137 $ctrl.updateLatLng = function (latlng) {138 if (!MapUtil.isValidLatLng(latlng)) {139 return;140 }141 MapState.setMapCenterLatLng(latlng);142 if (!leafletHelpers.isSameCenterOnMap(latlng, $ctrl.map)) {143 $ctrl.map.setView([latlng.lat, latlng.lng], latlng.zoom);144 $timeout(function () {145 // This fixes map size in dialogs146 $ctrl.map.invalidateSize({reset: true});147 });148 }149 };150 },151 link: function ($scope, element, attrs, ctrls) {152 var $ctrl = ctrls[0];153 var leafletCtrl = ctrls[1];154 leafletCtrl.getMap().then(function (map) {155 $ctrl.map = map;156 var geoLocationValue = $parse(attrs.rGeolocationCenter);157 var defaultZoomGetter = $parse(attrs.defaultZoom);158 $scope.$watch(geoLocationValue, function (geoLocation) {159 var defaultZoom = $scope.$eval(defaultZoomGetter);160 $ctrl.updateCenter(geoLocation, defaultZoom);161 });162 map.on('moveend', function () {163 MapState.setMapCenterLatLng({164 lat: map.getCenter().lat,165 lng: map.getCenter().lng,166 zoom: map.getZoom()167 });168 });169 });170 }171 };172 }173 )174 .directive('rGeolocationMarker',175 function ($parse, leafletMarkersHelpers, versionUrlPrefix, MapUtil, WGS84, GIS) {176 var location = {};177 function updateCoordinates(lat, lng) {178 location.latitude = lat;179 location.longitude = lng;180 }181 return {182 restrict: "A",183 scope: false,184 replace: false,185 require: 'leaflet',186 controller: function () {187 this.getLocation = function () {188 return location;189 };190 },191 link: function (scope, element, attrs, mapController) {192 var geoLocationGetter = $parse(attrs.rGeolocationMarker);193 var geoLocationEditableGetter = $parse(attrs.rGeolocationEditable);194 var rGeolocationMarkerForceFinland = $parse(attrs.rGeolocationMarkerForceFinland)();195 function _assignGeolocationToScope(lat, lng) {196 if (lat && lng) {197 geoLocationGetter.assign(scope, {198 latitude: lat,199 longitude: lng,200 accuracy: 0,201 source: 'MANUAL'202 });203 updateCoordinates(lat, lng);204 }205 }206 function _resolveGeolocationAndAssign(latlng) {207 var geoLocation = WGS84.toETRS(latlng.lat, latlng.lng);208 var lat = Math.round(geoLocation.lat);209 var lng = Math.round(geoLocation.lng);210 if (rGeolocationMarkerForceFinland) {211 var ok = function () {212 _assignGeolocationToScope(lat, lng);213 };214 var nok = function () {215 _assignGeolocationToScope(null, null);216 };217 GIS.getRhyForGeoLocation({latitude: lat, longitude: lng}).then(ok, nok);218 } else {219 _assignGeolocationToScope(lat, lng);220 }221 }222 function _createMarker(markerData) {223 var leafletMarker = leafletMarkersHelpers.createMarker(markerData);224 // Add event handler to update Geolocation after moving the marker225 leafletMarker.on('dragend', function (e) {226 _resolveGeolocationAndAssign(leafletMarker.getLatLng());227 scope.$digest();228 });229 return leafletMarker;230 }231 function _addMarker(map, geoLocation, draggable) {232 var markerData = WGS84.fromETRS(geoLocation.latitude, geoLocation.longitude);233 markerData.draggable = draggable;234 markerData.icon = {235 type: 'icon',236 icon: new L.Icon.Default({237 iconUrl: versionUrlPrefix + '/css/images/marker-icon.png',238 iconRetinaUrl: versionUrlPrefix + '/css/images/marker-icon-2x.png',239 shadowUrl: versionUrlPrefix + '/css/images/marker-shadow.png',240 iconSize: [25, 41],241 iconAnchor: [12, 41],242 popupAnchor: [1, -34],243 shadowSize: [41, 41]244 })245 };246 scope.leafletMarker = _createMarker(markerData);247 map.addLayer(scope.leafletMarker);248 // accuracy circle249 if (geoLocation.accuracy) {250 var accuracyCircleSettings = {weight: 2, opacity: 1, fillOpacity: 0.4};251 scope.leafletCircle = L.circle(markerData, geoLocation.accuracy, accuracyCircleSettings);252 scope.leafletCircle.addTo(map);253 }254 }255 function _removeMarker(map) {256 if (scope.leafletMarker) {257 leafletMarkersHelpers.deleteMarker(scope.leafletMarker, map, null);258 }259 if (scope.leafletCircle) {260 map.removeLayer(scope.leafletCircle);261 }262 }263 function _replaceMarker(map, geoLocation, markerEditable) {264 _removeMarker(map);265 _addMarker(map, geoLocation, markerEditable);266 }267 mapController.getMap().then(function (map) {268 var mapClickHandler = function (leafletEvent) {269 _resolveGeolocationAndAssign(leafletEvent.latlng);270 };271 scope.$watchGroup([geoLocationGetter, geoLocationEditableGetter], function (vals) {272 var geoLocation = vals[0],273 editable = vals[1];274 // Add event handler to set geoLocation selected position275 if (editable) {276 map.on('click', mapClickHandler);277 } else {278 map.off('click', mapClickHandler);279 }280 if (MapUtil.isValidGeoLocation(geoLocation)) {281 _replaceMarker(map, geoLocation, editable);282 updateCoordinates(geoLocation.latitude, geoLocation.longitude);283 } else {284 _removeMarker(map);285 }286 });287 });288 }289 };290 }291 )292 .directive('rGeolocationInput', function ($parse, WGS84) {293 function _withinBounds(latlng) {294 return latlng.lat >= 59 && latlng.lat <= 71 &&295 latlng.lng >= 19 && latlng.lng <= 32;296 }297 function _round(latlng) {298 latlng.lat = Math.round(latlng.lat);299 latlng.lng = Math.round(latlng.lng);300 return latlng;301 }302 function _filterFloat(value) {303 return (/^(\-|\+)?([0-9]+(\.[0-9]+)?)$/.test(value)) ? parseFloat(value) : null;304 }305 function _parseInput(inputFields) {306 var result = {307 lat: _filterFloat(inputFields.lat),308 lng: _filterFloat(inputFields.lng)309 };310 return isFinite(result.lat) && isFinite(result.lng) ? result : null;311 }312 function _toWGS84(latlng, inputCrs) {313 if (inputCrs === 'ETRS-TM35FIN') {314 return WGS84.fromETRS(latlng.lat, latlng.lng);315 } else if (inputCrs === 'KKJ') {316 return WGS84.fromKKJ(latlng.lat, latlng.lng);317 } else {318 return latlng;319 }320 }321 function _toInputFieldValues(geoLocation, crs) {322 if (!geoLocation) {323 return {};324 } else if (crs === 'ETRS-TM35FIN') {325 return {326 lat: geoLocation.latitude,327 lng: geoLocation.longitude328 };329 } else {330 var latlng = WGS84.fromETRS(geoLocation.latitude, geoLocation.longitude);331 if (crs === 'KKJ') {332 return _round(WGS84.toKKJ(latlng.lat, latlng.lng));333 } else {334 return latlng;335 }336 }337 }338 function _updateGeoLocation(geoLocation, inputFields, crs) {339 var latlng = _toWGS84(inputFields, crs);340 if (_withinBounds(latlng)) {341 var etrs = _round(WGS84.toETRS(latlng.lat, latlng.lng));342 geoLocation.latitude = etrs.lat;343 geoLocation.longitude = etrs.lng;344 geoLocation.source = 'MANUAL';345 return angular.copy(geoLocation);346 }347 return null;348 }349 return {350 restrict: 'A',351 scope: {352 geoLocation: '=rGeolocationInput'353 },354 templateUrl: function (elem, attr) {355 return attr.overriddenTemplate || 'common/map/geolocation_input.html';356 },357 controllerAs: '$ctrl',358 controller: function ($scope) {359 var $ctrl = this;360 $ctrl.coordinateSystems = ['ETRS-TM35FIN', 'WGS84', 'KKJ'];361 $ctrl.coordinateSystem = 'ETRS-TM35FIN';362 $ctrl.coordinatesInput = {lat: null, lng: null};363 // External model update364 $scope.$watch('geoLocation', function (geoLocation) {365 $ctrl.coordinatesInput = _toInputFieldValues(geoLocation, $ctrl.coordinateSystem);366 });367 // Input CRS option change368 $ctrl.coordinateSystemChanged = function () {369 $ctrl.coordinatesInput = _toInputFieldValues($scope.geoLocation, $ctrl.coordinateSystem);370 };371 $ctrl.setCoordinates = function () {372 var inputFields = _parseInput($ctrl.coordinatesInput);373 if (inputFields) {374 var newLocation = _updateGeoLocation($scope.geoLocation || {}, inputFields, $ctrl.coordinateSystem);375 if (newLocation) {376 $scope.geoLocation = newLocation;377 }378 }379 };380 }381 };382 })383 .directive('rNaturaAreaInfo', function($parse, WGS84, GIS) {384 return {385 restrict: "A",386 scope: false,387 replace: false,388 require: 'leaflet',389 link: function ($scope, element, attrs, mapController) {390 var geoLocationGetter = $parse(attrs.rGeolocationMarker);391 var naturaAreaInfoGetter = $parse(attrs.rNaturaAreaInfo);392 mapController.getMap().then(function (map) {393 $scope.$watch(geoLocationGetter, function (geoLocation) {394 if (_.isNil(geoLocation) || _.isNil(geoLocation.latitude) || _.isNil(geoLocation.longitude)) {395 return;396 }397 var storeResponse = function (rsp) {398 naturaAreaInfoGetter.assign($scope, rsp.data);399 };400 GIS.getNaturaAreaInfo(map, geoLocation).then(storeResponse);401 });402 });403 }404 };405 })406 .component('markerEditorMap', {407 templateUrl: 'common/map/marker-editor-map.html',408 transclude: true,409 bindings: {410 geolocation: '=',411 editable: '<'412 },413 controller: function (MapDefaults, MapState) {414 var $ctrl = this;415 $ctrl.$onInit = function () {416 $ctrl.mapEvents = MapDefaults.getMapBroadcastEvents(['click']);417 $ctrl.mapDefaults = MapDefaults.create();418 $ctrl.mapCenter = MapState.toGeoLocationOrDefault($ctrl.geolocation);419 };420 }...
storage.spec.js
Source:storage.spec.js
1import Storage from '../../src/app/storage';2jest.mock('../../src/api/ipGeoLocation');3jest.mock('../../src/api/foreCastAPI');4jest.mock('../../src/api/reverseGeoLocation');5describe('Storage', () => {6 describe('constructor', () => {7 it('defines properties', () => {8 const storage = new Storage();9 expect(storage.ipFetcher).toBeDefined();10 expect(storage.ipGeoLocation).toBeDefined();11 expect(storage.foreCastAPI).toBeDefined();12 expect(storage.reverseGeoLocation).toBeDefined();13 expect(storage.data).toBeDefined();14 expect(storage.currentDate).toBeDefined();15 });16 });17 describe('.update', () => {18 it('updates this.data', () => {19 const storage = new Storage();20 const initialData = storage.data;21 storage.update();22 expect(initialData).not.toEqual(storage.data);23 });24 it('calls .getLastUpdate', () => {25 const storage = new Storage();26 spyOn(storage, 'getLastUpdate');27 storage.update();28 expect(storage.getLastUpdate).toBeCalled();29 });30 });31 describe('.getLastUpdate', () => {32 it('returns formatted date string', () => {33 const storage = new Storage();34 const result = storage.getLastUpdate(new Date(2018, 11, 24, 10, 33));35 expect(result).toBe('10:33');36 });37 it('returns formatted date string with leading zeros', () => {38 const storage = new Storage();39 const result = storage.getLastUpdate(new Date(2018, 11, 24, 2, 5));40 expect(result).toBe('02:05');41 });42 });43 describe('async .getLocation', () => {44 describe('when last fetch still under and hour', () => {45 it('updates location', async () => {46 const storage = new Storage();47 localStorage.setItem('lastupdate', new Date().getTime());48 spyOn(storage.reverseGeoLocation, 'fetch').and.callThrough();49 spyOn(storage.foreCastAPI, 'fetch');50 spyOn(storage, 'update');51 await storage.getLocation(-23.5733, -46.6417);52 expect(storage.foreCastAPI.fetch).not.toBeCalledWith(-23.5733, -46.6417);53 expect(storage.reverseGeoLocation.fetch).toBeCalledWith(-23.5733, -46.6417);54 expect(storage.ipGeoLocation.data.city).toBe('Sundern');55 expect(storage.update).toBeCalled();56 });57 });58 describe('when last fetch still under and hour', () => {59 it('updates location and forecast', async () => {60 const storage = new Storage();61 localStorage.setItem('lastupdate', new Date(2018, 11, 24, 2, 5).getTime());62 spyOn(storage.reverseGeoLocation, 'fetch').and.callThrough();63 spyOn(storage.foreCastAPI, 'fetch').and.callThrough();64 spyOn(storage, 'update');65 await storage.getLocation(-23.5733, -46.6417);66 expect(storage.foreCastAPI.fetch).toBeCalledWith(-23.5733, -46.6417);67 expect(storage.reverseGeoLocation.fetch).toBeCalledWith(-23.5733, -46.6417);68 expect(storage.ipGeoLocation.data.city).toBe('Sundern');69 expect(storage.update).toBeCalled();70 });71 });72 });73 describe('.fetch', () => {74 it('calls through ._updateIP ._updateGeoLocation ._updateForecast .update', async () => {75 const storage = new Storage();76 spyOn(storage, '_updateIP');77 spyOn(storage, '_updateGeoLocation');78 spyOn(storage, '_updateForecast');79 spyOn(storage, 'update');80 await storage.fetch();81 expect(storage._updateIP).toBeCalled();82 expect(storage._updateGeoLocation).toBeCalled();83 expect(storage._updateForecast).toBeCalled();84 expect(storage.update).toBeCalled();85 });86 });87 describe('._updateIP', () => {88 describe('when IP already cached', () => {89 it('does not fetch IP', async () => {90 const storage = new Storage();91 localStorage.setItem('ip', 1111);92 spyOn(storage.ipFetcher, 'fetch');93 await storage._updateIP();94 expect(storage.ipFetcher.fetch).not.toBeCalled();95 });96 });97 describe('when IP not present', () => {98 it('does fetch IP', async () => {99 const storage = new Storage();100 localStorage.removeItem('ip');101 spyOn(storage.ipFetcher, 'fetch');102 await storage._updateIP();103 expect(storage.ipFetcher.fetch).toBeCalled();104 });105 });106 });107 describe('._updateGeoLocation', () => {108 describe('when geoLocation already cached', () => {109 it('does not fetch geoLocation', async () => {110 const storage = new Storage();111 localStorage.setItem('geoLocation', 1111);112 spyOn(storage.ipGeoLocation, 'fetch');113 await storage._updateGeoLocation();114 expect(storage.ipGeoLocation.fetch).not.toBeCalled();115 });116 });117 describe('when geoLocation not present', () => {118 it('does fetch geoLocation', async () => {119 const storage = new Storage();120 localStorage.removeItem('geoLocation');121 spyOn(storage.ipGeoLocation, 'fetch');122 await storage._updateGeoLocation();123 expect(storage.ipGeoLocation.fetch).toBeCalled();124 });125 });126 });127 describe('._updateForecast', () => {128 describe('when forecast already cached', () => {129 it('does not fetch forecast', async () => {130 const storage = new Storage();131 localStorage.setItem('forecast', 1111);132 spyOn(storage.foreCastAPI, 'fetch');133 await storage._updateForecast();134 expect(storage.foreCastAPI.fetch).not.toBeCalled();135 });136 });137 describe('when forecast not present', () => {138 it('does fetch forecast', async () => {139 const storage = new Storage();140 localStorage.removeItem('forecast');141 spyOn(storage.foreCastAPI, 'fetch');142 await storage._updateForecast();143 expect(storage.foreCastAPI.fetch).toBeCalled();144 });145 });146 });...
storage.js
Source:storage.js
1import IpGeoLocation from '../api/ipGeoLocation';2import ForeCastAPI from '../api/foreCastAPI';3import ReverseGeoLocation from '../api/reverseGeoLocation';4import IpFetcher from '../api/ipfetcher';5import timeConvert, { addLeadingZero } from '../helpers/time';6import icons from '../helpers/icons';7import weekdays from '../helpers/weekdays';8import initialState from '../initialState';9export default class Storage {10 constructor() {11 this.ipFetcher = new IpFetcher();12 this.ipGeoLocation = new IpGeoLocation();13 this.foreCastAPI = new ForeCastAPI(process.env.REACT_APP_DARK_SKY_API_CODE);14 this.reverseGeoLocation = new ReverseGeoLocation();15 this.data = { ...initialState };16 this.currentDate = new Date();17 }18 update() {19 this.data = {20 latitude: this.foreCastAPI.data.latitude,21 longitude: this.foreCastAPI.data.longitude,22 lastUpdate: this.getLastUpdate(this.currentDate),23 currentCondition: {24 ...initialState,25 location: this.ipGeoLocation.data.city,26 date: timeConvert(this.foreCastAPI.data.currently.time).localeDateString,27 temperature: Math.round(this.foreCastAPI.data.currently.temperature),28 weather: this.foreCastAPI.data.currently.summary29 },30 foreCastHourly: this.foreCastAPI.data.hourly.data.slice(0, 5).map((item) => ({31 time: timeConvert(item.time).hours,32 rainProbability: Math.round(item.precipProbability * 100),33 temperature: Math.round(item.temperature),34 icon: icons(item.icon).id35 })),36 foreCastDaily: this.foreCastAPI.data.daily.data.slice(1, 6).map(item => ({37 weekDay: weekdays(timeConvert(item.time).weekDay),38 rainProbability: Math.round(item.precipProbability * 100),39 icon: icons(item.icon).id,40 temperature: {41 max: Math.round(item.temperatureMax),42 min: Math.round(item.temperatureMin)43 }44 }))45 }46 }47 getLastUpdate(currentDate) {48 return `${addLeadingZero(currentDate.getHours())}:${addLeadingZero(currentDate.getMinutes())}`;49 }50 async _updateIP() {51 if (localStorage.getItem('ip')) {52 this.ipFetcher.ip = localStorage.getItem('ip');53 } else {54 await this.ipFetcher.fetch();55 localStorage.setItem('ip', this.ipFetcher.ip);56 }57 }58 async _updateGeoLocation() {59 if (localStorage.getItem('geoLocation')) {60 this.ipGeoLocation.data = JSON.parse(localStorage.getItem('geoLocation'));61 } else {62 await this.ipGeoLocation.fetch(this.ipFetcher.ip);63 localStorage.setItem('geoLocation', JSON.stringify(this.ipGeoLocation.data));64 }65 }66 async _updateForecast() {67 if (localStorage.getItem('forecast')) {68 this.foreCastAPI.data = JSON.parse(localStorage.getItem('forecast'));69 } else {70 await this.foreCastAPI.fetch(this.ipGeoLocation.data.latitude, this.ipGeoLocation.data.longitude);71 localStorage.setItem('lastupdate', new Date().getTime());72 localStorage.setItem('forecast', JSON.stringify(this.foreCastAPI.data));73 }74 }75 async fetch() {76 await this._updateIP();77 await this._updateGeoLocation();78 await this._updateForecast();79 this.update();80 }81 async getLocation(latitude, longitude) {82 this.currentDate = new Date();83 const prevDate = Number(localStorage.getItem('lastupdate'));84 const hoursDiff = Math.abs(this.currentDate.getTime() - prevDate) / 3600000;85 this.foreCastAPI.data.latitude = latitude;86 this.foreCastAPI.data.longitude = longitude;87 this.data.lastUpdate = this.getLastUpdate(this.currentDate);88 await this.reverseGeoLocation.fetch(latitude, longitude);89 if (hoursDiff > 1.05) {90 await this.foreCastAPI.fetch(latitude, longitude);91 localStorage.setItem('lastupdate', this.currentDate.getTime());92 localStorage.setItem('forecast', JSON.stringify(this.foreCastAPI.data));93 }94 this.ipGeoLocation.data.city = this.reverseGeoLocation.data[0].city || this.reverseGeoLocation.data[0].state;95 this.update();96 }...
GeoLocation.js
Source:GeoLocation.js
1import React, { Component } from 'react';2import {3 AppRegistry,4} from 'react-native';5export default class GeoLocation extends Component {6 constructor(props){7 super(props)8 this.state = {9 region: this.props.region ? this.props.region : {10 latitude: this.props.markerCoordinate? this.props.markerCoordinate.latitude: 43.464258,11 longitude: this.props.markerCoordinate? this.props.markerCoordinate.longitude: -80.520410,12 latitudeDelta: 0.015,13 longitudeDelta: 0.0121,14 },15 markerCoordinate: this.props.markerCoordinate ? this.props.markerCoordinate : {16 latitude: 43.464258,17 longitude: -80.520410,18 },19 }20 }21 _onMapPress(data) {22 if (data.nativeEvent.coordinate) {23 this.setState({24 markerCoordinate: data.nativeEvent.coordinate25 })26 }27 }28 29 _onDragMarkerEnd(data) {30 if (data.nativeEvent.coordinate) {31 this.setState({32 markerCoordinate: data.nativeEvent.coordinate33 })34 }35 }36 37 _onMarkerPress(data) {38 console.log("marker")39 }40 41 _updateGeoLocation() {42 this.props.modalParent._updateGeoCoordinate(this.state.markerCoordinate)43 }44 45 _leaveModal() {46 this.props.modalParent._setModalVisible(false)47 }48}...
acat.geolocation.dialog.controller.js
Source:acat.geolocation.dialog.controller.js
1(function (angular) {2 "use strict";3 angular.module("app.processing")4 .controller("GeoLocationController", GeoLocationController);5 GeoLocationController.$inject = ['$mdDialog','data'];6 function GeoLocationController($mdDialog,data) {7 var vm = this;8 vm.gps_location = { polygon: [],single_point:{}};9 console.log("data",data);10 vm.cancel = _cancel;11 vm.updateGeoLocation = _updateGeoLocation;12 vm.addEditGeoLocation = _addEditGeoLocation;13 function _cancel() {14 $mdDialog.cancel();15 }16 function _updateGeoLocation(geolocation) {17 $mdDialog.hide("hello");18 }19 function _addEditGeoLocation(geolocation) {20 vm.gps_location.polygon.push(angular.copy(geolocation));21 // $mdDialog.hide("hello");22 }23 }...
Using AI Code Generation
1const { _updateGeolocation } = 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 _updateGeolocation(context, { longitude: 12.34, latitude: 56.78 });7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const context = await browser.newContext();12 await context._updateGeolocation({ longitude: 12.34, latitude: 56.78 });13})();14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 await context.setGeolocation({ longitude: 12.34, latitude: 56.78 });19 await context.clearPermissions();20})();21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch();24 const context = await browser.newContext();25 const page = await context.newPage();26 await page.click('text="Your location"');27 await page.click('text="Always share"');28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 await context.grantPermissions(['geolocation']);34 const page = await context.newPage();35 await page.click('text="Your location"');36 await page.click('text="Always share"');37 await context.clearPermissions();38})();39const { chromium } = require('playwright');40(async () => {41 const browser = await chromium.launch();42 const context = await browser.newContext();43 await context.grantPermissions(['geolocation']);44 const page = await context.newPage();45 await page.click('text="Allow"');46 await context.clearPermissions();47})();48const { chromium } = require('playwright
Using AI Code Generation
1const { _updateGeolocation } = require('playwright/lib/server/chromium/crBrowser');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 await _updateGeolocation(context, {7 });8 const page = await context.newPage();9 await page.waitForLoadState('domcontentloaded');10 await page.screenshot({ path: 'geolocation.png' });11 await browser.close();12})();13const { _updateDeviceMetricsOverride } = require('playwright/lib/server/chromium/crBrowser');14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 await _updateDeviceMetricsOverride(context, {19 });20 const page = await context.newPage();21 await page.waitForLoadState('domcontentloaded');22 await page.screenshot({ path: 'screenshot.png' });23 await browser.close();24})();
Using AI Code Generation
1const { _updateGeolocation } = require('playwright-core/lib/server/chromium/crBrowser.js');2const { chromium } = require('playwright-core');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext({ geolocation: { latitude: 51.508, longitude: 0.125 } });6 const page = await context.newPage();7 await page.waitForTimeout(5000);8 await _updateGeolocation(page, { latitude: 48.8566, longitude: 2.3522 });9 await page.waitForTimeout(5000);10 await browser.close();11})();12const { _updateGeolocation } = require('playwright-core/lib/server/chromium/crBrowser.js');13const { chromium } = require('playwright-core');14(async () => {15 const browser = await chromium.launch({ headless: false, args: ['--no-sandbox', '--disable-setuid-sandbox'] });16 const context = await browser.newContext({ geolocation: { latitude: 51.508, longitude: 0.125 } });17 const page = await context.newPage();18 await page.waitForTimeout(5000);19 await _updateGeolocation(page, { latitude: 48.8566, longitude: 2.3522 });20 await page.waitForTimeout(5000);21 await browser.close();22})();23 at CDPSession.send (/home/playwright/node_modules/playwright-core/lib/cjs/server/cjs/common/Connection.js:205:35)24 at Page._updateGeolocation (/home/playwright/node_modules/playwright-core/lib/cjs/server/cjs/common/Page.js:322:33)25 at Page._onClosed (/home/playwright/node_modules/playwright-core/lib/cjs/server
Using AI Code Generation
1const { _updateGeolocation } = require('playwright-core/lib/server/chromium/crBrowser');2const { chromium } = require('playwright-core');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await _updateGeolocation(page, { latitude: 51.5074, longitude: 0.1278 });8 await page.screenshot({ path: 'example.png' });9 await browser.close();10})();
Using AI Code Generation
1const { _updateGeolocation } = require('playwright/lib/server/chromium/crBrowser');2const { chromium } = require('playwright');3const browser = await chromium.launch();4const context = await browser.newContext();5await _updateGeolocation(context, { longitude: 0, latitude: 0 });6await browser.close();7const { _updateGeolocation } = require('playwright/lib/server/chromium/crBrowser');8const { chromium } = require('playwright');9const browser = await chromium.launch();10const context = await browser.newContext();11await _updateGeolocation(context, { longitude: 0, latitude: 0 });12await browser.close();13const { _updateGeolocation } = require('playwright/lib/server/chromium/crBrowser');14const { chromium } = require('playwright');15const browser = await chromium.launch();16const context = await browser.newContext();17await _updateGeolocation(context, { longitude: 0, latitude: 0 });18await browser.close();19const { _updateGeolocation } = require('playwright/lib/server/chromium/crBrowser');20const { chromium } = require('playwright');21const browser = await chromium.launch();22const context = await browser.newContext();23await _updateGeolocation(context, { longitude: 0, latitude: 0 });24await browser.close();25const { _updateGeolocation } = require('playwright/lib/server/chromium/crBrowser');26const { chromium } = require('playwright');27const browser = await chromium.launch();28const context = await browser.newContext();29await _updateGeolocation(context, { longitude: 0, latitude: 0 });30await browser.close();31const { _updateGeolocation } = require('playwright/lib/server/chromium/crBrowser');32const { chromium } = require('playwright');33const browser = await chromium.launch();34const context = await browser.newContext();35await _updateGeolocation(context, { longitude: 0
Using AI Code Generation
1const { PlaywrightInternal } = require('playwright');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 await PlaywrightInternal.updateGeolocation(page, { latitude: 51.508, longitude: -0.11 });8 await page.waitForTimeout(5000);9 await browser.close();10})();11 at CDPSession._onMessage (/Users/raghav/Desktop/playwright/node_modules/playwright-core/lib/cjs/pw-run.js:320:15)12 at CDPSession.emit (events.js:315:20)13 at CDPSession._onMessage (/Users/raghav/Desktop/playwright/node_modules/playwright-core/lib/cjs/pw-run.js:320:15)14 at CDPSession.emit (events.js:315:20)15 at CDPSession._onMessage (/Users/raghav/Desktop/playwright/node_modules/playwright-core/lib/cjs/pw-run.js:320:15)16 at CDPSession.emit (events.js:315:20)17 at CDPSession._onMessage (/Users/raghav/Desktop/playwright/node_modules/playwright-core/lib/cjs/pw-run.js:320:15)18 at CDPSession.emit (events.js:315:20)19 at CDPSession._onMessage (/Users/raghav/Desktop/playwright/node_modules/playwright-core/lib/cjs/pw-run.js:320:15)20 at CDPSession.emit (events.js:315:20)
Using AI Code Generation
1const geolocation = {latitude: 51.50853, longitude: -0.12574};2await page._client.send('Emulation.setGeolocationOverride', geolocation);3const geolocation = {latitude: 51.50853, longitude: -0.12574};4await context._browser._defaultContext._browserContext._updateGeolocation(geolocation);5const geolocation = {latitude: 51.50853, longitude: -0.12574};6await context._browser._defaultContext._updateGeolocation(geolocation);7const geolocation = {latitude: 51.50853, longitude: -0.12574};8await context._updateGeolocation(geolocation);9const geolocation = {latitude: 51.50853, longitude: -0.12574};10await context._browserContext._updateGeolocation(geolocation);11const geolocation = {latitude: 51.50853, longitude: -0.12574};12await context._browser._browserContext._updateGeolocation(geolocation);13const geolocation = {latitude: 51.50853, longitude: -0.12574};14await context._page._browserContext._updateGeolocation(geolocation);15const geolocation = {latitude: 51.50853, longitude: -0.12574};16await context._page._browser._browserContext._updateGeolocation(geolocation);17const geolocation = {latitude: 51.50853, longitude: -0.12574};18await context._page._browser._browserContext._browser._updateGeolocation(geolocation);19const geolocation = {latitude: 51.50853, longitude: -0.12574};
Using AI Code Generation
1const { _updateGeolocation } = require('playwright-core/lib/server/chromium/crBrowser');2const { chromium } = require('playwright-core');3const { test } = require('@playwright/test');4test('test', async ({ page }) => {5 const context = await browser.newContext();6 const page = await context.newPage();7 await _updateGeolocation(page, { latitude: 51.508530, longitude: -0.076132 });8 await page.waitForTimeout(5000);9 await browser.close();10});
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!!