How to use isNavigationRequest method in Puppeteer

Best JavaScript code snippet using puppeteer

network.spec.js

Source:network.spec.js Github

copy

Full Screen

...319 const requests = new Map();320 page.on('request', request => requests.set(request.url().split('/').pop(), request));321 server.setRedirect('/rrredirect', '/frames/one-frame.html');322 await page.goto(server.PREFIX + '/rrredirect');323 expect(requests.get('rrredirect').isNavigationRequest()).toBe(true);324 expect(requests.get('one-frame.html').isNavigationRequest()).toBe(true);325 expect(requests.get('frame.html').isNavigationRequest()).toBe(true);326 expect(requests.get('script.js').isNavigationRequest()).toBe(false);327 expect(requests.get('style.css').isNavigationRequest()).toBe(false);328 });329 it('should work with request interception', async({page, server}) => {330 const requests = new Map();331 page.on('request', request => {332 requests.set(request.url().split('/').pop(), request);333 request.continue();334 });335 await page.setRequestInterception(true);336 server.setRedirect('/rrredirect', '/frames/one-frame.html');337 await page.goto(server.PREFIX + '/rrredirect');338 expect(requests.get('rrredirect').isNavigationRequest()).toBe(true);339 expect(requests.get('one-frame.html').isNavigationRequest()).toBe(true);340 expect(requests.get('frame.html').isNavigationRequest()).toBe(true);341 expect(requests.get('script.js').isNavigationRequest()).toBe(false);342 expect(requests.get('style.css').isNavigationRequest()).toBe(false);343 });344 it('should work when navigating to image', async({page, server}) => {345 const requests = [];346 page.on('request', request => requests.push(request));347 await page.goto(server.PREFIX + '/pptr.png');348 expect(requests[0].isNavigationRequest()).toBe(true);349 });350 });351 describe('Page.setExtraHTTPHeaders', function() {352 it('should work', async({page, server}) => {353 await page.setExtraHTTPHeaders({354 foo: 'bar'355 });356 const [request] = await Promise.all([357 server.waitForRequest('/empty.html'),358 page.goto(server.EMPTY_PAGE),359 ]);360 expect(request.headers['foo']).toBe('bar');361 });362 it('should throw for non-string header values', async({page, server}) => {...

Full Screen

Full Screen

record.js

Source:record.js Github

copy

Full Screen

...203 true, {},204 baseReport, {205 url: request.url(),206 httpStatusCode: response.status(),207 isNavigationRequest: request.isNavigationRequest(),208 redirectChain,209 resourceType: request.resourceType(),210 trials: 'TODO',211 },212 request.userData,213 meta214 );215216 if ('content-type' in response.headers()) {217 record.contentType = response.headers()['content-type'].split(';')[0].trim();218 }219220 record.httpStatusCode = getFinalStatus(record);221222 const {223 finalUrl224 } = getFinalUrl({225 record,226 httpStatusCode: response.status(),227 headers: response.headers()228 });229230 record.finalUrl = finalUrl;231232 delete record.userData;233234 // record.body = null;235 return record;236 }237238 if (response && '_client' in response) {239 // apify request class && puppeteer Response class240 // This is a navigation response241 const record = extend(242 true,243 baseReport, {244 /** @member {string} [urlData] - Url as found when crawling */245 url: request.url,246 httpStatusCode: response.status(),247 isNavigationRequest: response.request().isNavigationRequest(),248 redirectChain: getRedirectionChain(249 response.request().redirectChain(),250 request.url251 ),252 resourceType: response.request().resourceType(),253 trials: request.retryCount254 },255 request.userData,256 meta257 );258259 if ('content-type' in response.headers()) {260 record.contentType = response.headers()['content-type'].split(';')[0].trim();261 }262263 record.httpStatusCode = getFinalStatus(record);264265 const {266 finalUrl267 } = getFinalUrl({268 record,269 httpStatusCode: response.status(),270 headers: response.headers(),271 body: meta.body272 });273274 record.finalUrl = finalUrl;275276 delete record.userData;277 delete record.uniqueKey;278279 return record;280 }281282 if (response && response.constructor.name === 'IncomingMessage') {283 // apify request class && (request-promise-native) IncomingMessage class response284 // This is a basicCrawler response285286 const redirectChain = getRedirectionChain(287 response.request._redirect.redirects,288 request.url289 );290291 const record = extend(292 true,293 baseReport, {294 /** @member {string} [urlData] - Url as found when crawling */295 url: request.url,296 httpStatusCode: response.statusCode,297 isNavigationRequest: 'TODO',298 redirectChain,299 resourceType_: ResourceType.fromMimeType(300 response.headers['content-type']301 ).name(),302 trials: request.retryCount303 },304 request.userData,305 meta306 );307308 if ('content-type' in response.headers) {309 record.contentType = response.headers['content-type'].split(';')[0].trim();310 }311312 if ('content-length' in response.headers) {313 record.contentLength = response.headers['content-length'];314 }315316 record.httpStatusCode = getFinalStatus(record);317318 const {319 finalUrl320 } = getFinalUrl({321 record,322 httpStatusCode: response.statusCode,323 headers: response.headers,324 body: meta.body325 });326327 record.finalUrl = finalUrl;328329 delete record.userData;330331 return record;332 }333334 // This is a mailto: link335 // args: link, request, meta336 // The request argument only has a .userData property.337338 const record = extend(339 true, {},340 baseReport, {341 /** @member {string} [urlData] - Url as found when crawling */342 url: request.url,343 finalUrl: normalizeUrl(request.url),344 isNavigationRequest: 'TODO',345 redirectChain: [],346 resourceType: 'TODO',347 trials: 0348 },349 request.userData,350 meta351 );352353 delete record.userData;354355 return record;356}357358export function handleFailedRequest(request, error, meta) {359 // apify request class360 console.me(inspect(request))361 const reports = captureErrors(request.userData.reports);362 //const _reports = request.userData.reports;363 delete request.userData.reports;364365 const baseReport = extend(true, {}, defaultOpts, {366 reports,367 //_reports,368 trials: request.retryCount,369 created: new Date().toISOString(),370 status: null371 });372373 if (meta._from === 'onNavigationRequestFailed') {374 // console.me(captureErrors(request.errorMessages))375 const record = extend(376 true, {},377 baseReport, {378 url: request.url,379 isNavigationRequest: true,380 redirectChain: [],381 requestErrorMessages: request.errorMessages382 },383 request.userData,384 meta385 );386387 delete record.userData;388 // console.z(record)389 return record;390 }391392 if (meta._from === 'onAssetRequestFailed') {393 const pupRequest = error;394395 const record = extend(396 true, {},397 baseReport, {398 url: request.url,399 isNavigationRequest: pupRequest.isNavigationRequest(),400 redirectChain: pupRequest.redirectChain(),401 resourceType: pupRequest.resourceType(),402 status: pupRequest.failure().errorText,403 reports_: captureErrors(pupRequest.failure().errorText)404 },405 request.userData,406 meta407 );408409 delete record.userData;410411 return record;412 }413} ...

Full Screen

Full Screen

intercept.test.js

Source:intercept.test.js Github

copy

Full Screen

1const expect = require('chai').expect;2const rewire = require('rewire');3let fetchHandler = rewire('../../lib/handlers/fetchHandler');4const test_name = 'Intercept';5describe(test_name, () => {6 let actualOption;7 beforeEach(() => {8 fetchHandler.__set__('fetch', {9 enable: () => {},10 requestPaused: () => {},11 continueRequest: (options) => {12 actualOption = options;13 return Promise.resolve();14 },15 failRequest: (options) => {16 actualOption = options;17 return Promise.resolve();18 },19 fulfillRequest: (options) => {20 actualOption = options;21 return Promise.resolve();22 },23 });24 });25 afterEach(() => {26 actualOption = null;27 fetchHandler.resetInterceptors();28 const createdSessionListener = fetchHandler.__get__('createdSessionListener');29 fetchHandler.__get__('eventHandler').removeListener('createdSession', createdSessionListener);30 fetchHandler = rewire('../../lib/handlers/fetchHandler');31 fetchHandler.__get__('eventHandler').removeListener('createdSession', createdSessionListener);32 });33 it('Check redirection using interception', async () => {34 fetchHandler.addInterceptor({35 requestUrl: 'www.google.com',36 action: 'www.ibibo.com',37 });38 fetchHandler.handleInterceptor({39 requestId: 'requestId',40 request: {41 url: 'http://www.google.com',42 method: 'GET',43 },44 resourceType: 'Document',45 isNavigationRequest: true,46 });47 expect(actualOption.url).to.equal('http://www.ibibo.com');48 });49 it('Block url', async () => {50 fetchHandler.addInterceptor({ requestUrl: 'www.google.com' });51 fetchHandler.handleInterceptor({52 requestId: 'requestId',53 request: {54 url: 'http://www.google.com',55 method: 'GET',56 },57 resourceType: 'Document',58 isNavigationRequest: true,59 });60 expect(actualOption.errorReason).to.equal('Failed');61 });62 it('Mock Response', async () => {63 fetchHandler.addInterceptor({64 requestUrl: 'http://localhost:3000/api/customers/11',65 action: {66 body: {67 id: 11,68 firstName: 'ward',69 lastName: 'bell',70 gender: 'male',71 address: '12345 Central St.',72 city: 'Los Angeles',73 state: { abbreviation: 'CA', name: 'California' },74 latitude: 34.042552,75 longitude: -118.266429,76 },77 },78 });79 fetchHandler.handleInterceptor({80 requestId: 'requestId',81 request: {82 url: 'http://localhost:3000/api/customers/11',83 method: 'GET',84 },85 resourceType: 'Document',86 isNavigationRequest: true,87 });88 let res = Buffer.from(actualOption.body, 'base64').toString('binary');89 expect(res).to.include('12345 Central St.');90 });91 it('Mock Response with empty body', async () => {92 fetchHandler.addInterceptor({93 requestUrl: 'http://localhost:3000/api/customers/11',94 action: {},95 });96 let req = {97 requestId: 'requestId',98 request: {99 url: 'http://localhost:3000/api/customers/11',100 method: 'GET',101 },102 resourceType: 'Document',103 isNavigationRequest: true,104 };105 expect(() => {106 fetchHandler.handleInterceptor(req);107 }).to.not.throw();108 });109 it('More than one intercept added for the same requestUrl', async () => {110 let actualConsoleWarn;111 console.warn = (log) => {112 actualConsoleWarn = log;113 };114 fetchHandler.addInterceptor({115 requestUrl: 'www.google.com',116 action: 'www.ibibo.com',117 });118 fetchHandler.addInterceptor({119 requestUrl: 'www.google.com',120 action: 'www.gauge.org',121 });122 fetchHandler.handleInterceptor({123 requestId: 'requestId',124 request: {125 url: 'http://www.google.com',126 method: 'GET',127 },128 resourceType: 'Document',129 isNavigationRequest: true,130 });131 let warningMessage =132 'WARNING: More than one intercept ["www.google.com","www.google.com"] found for request "http://www.google.com".\n Applying: intercept("www.google.com", "www.gauge.org")';133 expect(actualConsoleWarn).to.equal(warningMessage);134 expect(actualOption.url).to.equal('http://www.gauge.org');135 });136 describe('Intercept with count added', async () => {137 let count = 3;138 beforeEach(() => {139 fetchHandler.addInterceptor({140 requestUrl: 'www.google.com',141 action: 'www.gauge.org',142 count,143 });144 });145 it('intercepts requestUrl', async () => {146 for (var i = 0; i < count + 1; i++) {147 fetchHandler.handleInterceptor({148 requestId: 'requestId',149 request: {150 url: 'http://www.google.com',151 method: 'GET',152 },153 resourceType: 'Document',154 isNavigationRequest: true,155 });156 var result = count === i ? undefined : 'http://www.gauge.org';157 expect(actualOption.url).to.equal(result);158 }159 });160 it('maintains count amidst interleaving matched requests', async () => {161 for (var i = 0; i < count + 1; i++) {162 fetchHandler.handleInterceptor({163 requestId: 'otherRequestId',164 request: {165 url: 'http://www.otherrequest.com',166 method: 'GET',167 },168 resourceType: 'Document',169 isNavigationRequest: true,170 });171 fetchHandler.handleInterceptor({172 requestId: 'requestId',173 request: {174 url: 'http://www.google.com',175 method: 'GET',176 },177 resourceType: 'Document',178 isNavigationRequest: true,179 });180 var result = count === i ? undefined : 'http://www.gauge.org';181 expect(actualOption.url).to.equal(result);182 }183 });184 });185 it('reset intercept for the requestUrl if interceptor is present for the url', async () => {186 fetchHandler.addInterceptor({187 requestUrl: 'www.google.com',188 action: 'www.gauge.org',189 });190 var result = fetchHandler.resetInterceptor('www.google.com');191 fetchHandler.handleInterceptor({192 requestId: 'requestId',193 request: {194 url: 'http://www.google.com',195 method: 'GET',196 },197 resourceType: 'Document',198 isNavigationRequest: true,199 });200 expect(actualOption.url).to.equal(undefined);201 expect(result).to.equal(true);202 });203 it('reset intercept returns false if intercept does not exist for the requestUrl', async () => {204 var result = fetchHandler.resetInterceptor('www.google.com');205 expect(result).to.equal(false);206 });207 it('reset interceptors should set interceptors empty array and userEnabledIntercept false', async () => {208 fetchHandler.__set__('interceptors', ['intercept1', 'intercept2']);209 fetchHandler.__set__('userEnabledIntercept', true);210 fetchHandler.resetInterceptors();211 expect(fetchHandler.__get__('interceptors')).to.be.empty;212 expect(fetchHandler.__get__('userEnabledIntercept')).to.be.false;213 });214 it('add interceptor should put a entry in interceptors', async () => {215 const intercept = { request: 'action' };216 fetchHandler.addInterceptor(intercept);217 expect(fetchHandler.__get__('interceptors')[0]).to.deep.equal(intercept);218 });219 it('add interceptor should call enableFetchIntercept for the first time and set userEnabledIntercept to true', async () => {220 let called = false;221 fetchHandler.__set__('enableFetchIntercept', () => {222 called = true;223 });224 fetchHandler.addInterceptor('intercept');225 expect(fetchHandler.__get__('userEnabledIntercept')).to.be.true;226 expect(called).to.be.true;227 });228 it('add interceptor should not call enableFetchIntercept if userEnabledIntercept is set to true', async () => {229 let called = false;230 fetchHandler.__set__('enableFetchIntercept', () => {231 called = true;232 });233 fetchHandler.__set__('userEnabledIntercept', true);234 fetchHandler.addInterceptor('intercept');235 expect(fetchHandler.__get__('userEnabledIntercept')).to.be.true;236 expect(called).to.be.false;237 });238 it('createdSessionListener should call enableFetchIntercept if userEnabledIntercept is set to true', async () => {239 let called = false;240 fetchHandler.__set__('enableFetchIntercept', () => {241 called = true;242 });243 fetchHandler.__set__('userEnabledIntercept', true);244 fetchHandler.__get__('createdSessionListener')({ Fetch: 'domain' });245 expect(fetchHandler.__get__('userEnabledIntercept')).to.be.true;246 expect(called).to.be.true;247 });248 it('createdSessionListener should not call enableFetchIntercept if userEnabledIntercept is set to false', async () => {249 let called = false;250 fetchHandler.__set__('enableFetchIntercept', () => {251 called = true;252 });253 fetchHandler.__set__('userEnabledIntercept', false);254 fetchHandler.__get__('createdSessionListener')({ Fetch: 'domain' });255 expect(fetchHandler.__get__('userEnabledIntercept')).to.be.false;256 expect(called).to.be.false;257 });...

Full Screen

Full Screen

browser_resources_network_events.js

Source:browser_resources_network_events.js Github

copy

Full Screen

1/* Any copyright is dedicated to the Public Domain.2 http://creativecommons.org/publicdomain/zero/1.0/ */3"use strict";4// Test the ResourceCommand API around NETWORK_EVENT5const ResourceCommand = require("devtools/shared/commands/resource/resource-command");6// We are borrowing tests from the netmonitor frontend7const NETMONITOR_TEST_FOLDER =8 "https://example.com/browser/devtools/client/netmonitor/test/";9const CSP_URL = `${NETMONITOR_TEST_FOLDER}html_csp-test-page.html`;10const JS_CSP_URL = `${NETMONITOR_TEST_FOLDER}js_websocket-worker-test.js`;11const CSS_CSP_URL = `${NETMONITOR_TEST_FOLDER}internal-loaded.css`;12const CSP_BLOCKED_REASON_CODE = 4000;13add_task(async function testContentProcessRequests() {14 info(`Tests for NETWORK_EVENT resources fired from the content process`);15 const expectedAvailable = [16 {17 url: CSP_URL,18 method: "GET",19 isNavigationRequest: true,20 },21 {22 url: JS_CSP_URL,23 method: "GET",24 blockedReason: CSP_BLOCKED_REASON_CODE,25 isNavigationRequest: false,26 },27 {28 url: CSS_CSP_URL,29 method: "GET",30 blockedReason: CSP_BLOCKED_REASON_CODE,31 isNavigationRequest: false,32 },33 ];34 const expectedUpdated = [35 {36 url: CSP_URL,37 method: "GET",38 isNavigationRequest: true,39 },40 {41 url: JS_CSP_URL,42 method: "GET",43 blockedReason: CSP_BLOCKED_REASON_CODE,44 isNavigationRequest: false,45 },46 {47 url: CSS_CSP_URL,48 method: "GET",49 blockedReason: CSP_BLOCKED_REASON_CODE,50 isNavigationRequest: false,51 },52 ];53 await assertNetworkResourcesOnPage(54 CSP_URL,55 expectedAvailable,56 expectedUpdated57 );58});59add_task(async function testCanceledRequest() {60 info(`Tests for NETWORK_EVENT resources with a canceled request`);61 // Do a XHR request that we cancel against a slow loading page62 const requestUrl =63 "https://example.org/document-builder.sjs?delay=1000&html=foo";64 const html =65 "<!DOCTYPE html><script>(" +66 function(xhrUrl) {67 const xhr = new XMLHttpRequest();68 xhr.open("GET", xhrUrl);69 xhr.send(null);70 } +71 ")(" +72 JSON.stringify(requestUrl) +73 ")</script>";74 const pageUrl =75 "https://example.org/document-builder.sjs?html=" + encodeURIComponent(html);76 const expectedAvailable = [77 {78 url: pageUrl,79 method: "GET",80 isNavigationRequest: true,81 },82 {83 url: requestUrl,84 method: "GET",85 isNavigationRequest: false,86 blockedReason: "NS_BINDING_ABORTED",87 },88 ];89 const expectedUpdated = [90 {91 url: pageUrl,92 method: "GET",93 isNavigationRequest: true,94 },95 {96 url: requestUrl,97 method: "GET",98 isNavigationRequest: false,99 blockedReason: "NS_BINDING_ABORTED",100 },101 ];102 // Register a one-off listener to cancel the XHR request103 // Using XMLHttpRequest's abort() method from the content process104 // isn't reliable and would introduce many race condition in the test.105 // Canceling the request via nsIRequest.cancel privileged method,106 // from the parent process is much more reliable.107 const observer = {108 QueryInterface: ChromeUtils.generateQI(["nsIObserver"]),109 observe(subject, topic, data) {110 subject = subject.QueryInterface(Ci.nsIHttpChannel);111 if (subject.URI.spec == requestUrl) {112 subject.cancel(Cr.NS_BINDING_ABORTED);113 Services.obs.removeObserver(observer, "http-on-modify-request");114 }115 },116 };117 Services.obs.addObserver(observer, "http-on-modify-request");118 await assertNetworkResourcesOnPage(119 pageUrl,120 expectedAvailable,121 expectedUpdated122 );123});124async function assertNetworkResourcesOnPage(125 url,126 expectedAvailable,127 expectedUpdated128) {129 // First open a blank document to avoid spawning any request130 const tab = await addTab("about:blank");131 const commands = await CommandsFactory.forTab(tab);132 await commands.targetCommand.startListening();133 const { resourceCommand } = commands;134 const onAvailable = resources => {135 for (const resource of resources) {136 // Immediately assert the resource, as the same resource object137 // will be notified to onUpdated and so if we assert it later138 // we will not highlight attributes that aren't set yet from onAvailable.139 const idx = expectedAvailable.findIndex(e => e.url === resource.url);140 ok(141 idx != -1,142 "Found a matching available notification for: " + resource.url143 );144 // Remove the match from the list in case there is many requests with the same url145 const [expected] = expectedAvailable.splice(idx, 1);146 assertResources(resource, expected);147 }148 };149 const onUpdated = updates => {150 for (const { resource } of updates) {151 const idx = expectedUpdated.findIndex(e => e.url === resource.url);152 ok(153 idx != -1,154 "Found a matching updated notification for: " + resource.url155 );156 // Remove the match from the list in case there is many requests with the same url157 const [expected] = expectedUpdated.splice(idx, 1);158 assertResources(resource, expected);159 }160 };161 // Start observing for network events before loading the test page162 await resourceCommand.watchResources([resourceCommand.TYPES.NETWORK_EVENT], {163 onAvailable,164 onUpdated,165 });166 // Load the test page that fires network requests167 const onLoaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);168 BrowserTestUtils.loadURI(gBrowser.selectedBrowser, url);169 await onLoaded;170 // Make sure we processed all the expected request updates171 await waitFor(172 () => expectedAvailable.length == 0,173 "Wait for all expected available notifications"174 );175 await waitFor(176 () => expectedUpdated.length == 0,177 "Wait for all expected updated notifications"178 );179 resourceCommand.unwatchResources([resourceCommand.TYPES.NETWORK_EVENT], {180 onAvailable,181 onUpdated,182 });183 await commands.destroy();184 BrowserTestUtils.removeTab(tab);185}186function assertResources(actual, expected) {187 is(188 actual.resourceType,189 ResourceCommand.TYPES.NETWORK_EVENT,190 "The resource type is correct"191 );192 for (const name in expected) {193 is(actual[name], expected[name], `The '${name}' attribute is correct`);194 }...

Full Screen

Full Screen

finnishTransportService.js

Source:finnishTransportService.js Github

copy

Full Screen

1import {DOMParser} from 'xmldom';2let bottomLeftLongitude = 24.755115;3let bottomLeftLatitude = 60.107362;4let topRightLongitude = 25.068056;5let topRightLatitude = 60.204050;6const LATITUDE_DELTA_FOR_LINES_AND_BEACONS = 0.067const LONGITUDE_DELTA_FOR_LINES_AND_BEACONS = 0.168let isNavigationRequest= true;9let isBeaconRequest= true;10const fetchLightBeacons = async () => {11 return fetch('https://julkinen.vayla.fi/inspirepalvelu/avoin/wms?request=getmap&LAYERS=loistot&WIDTH=1400&HEIGHT=1400&FORMAT=application/vnd.google-earth.kml+xml&bbox='+bottomLeftLongitude+','+bottomLeftLatitude+','+topRightLongitude+','+topRightLatitude+'&srs=CRS:84').12 then(response => response.text()).13 then(string => {14 const parser = new DOMParser();15 const xmlDoc = parser.parseFromString(string, 'text/xml');16 const numberOfPlaceMarks = xmlDoc.getElementsByTagName('Placemark').length;17 const lightCoordinates = [];18 for (let index = 0; index < numberOfPlaceMarks; index++) {19 let coordinateAsString = xmlDoc.getElementsByTagName(20 'Placemark')[index].getElementsByTagName(21 'Point')[0].getElementsByTagName(22 'coordinates')[0].childNodes[0].nodeValue.split(',');23 let coordinates = {24 longitude: +coordinateAsString[0],25 latitude: +coordinateAsString[1],26 };27 lightCoordinates.push(coordinates);28 }29 isBeaconRequest = false;30 return lightCoordinates;31 })32 .catch(error => {33 console.log(error.message);34 });35};36const fetchNavigationLines = async () => {37 return fetch( 'https://julkinen.vayla.fi/inspirepalvelu/avoin/wms?request=getmap&LAYERS=navigointilinjat&WIDTH=1400&HEIGHT=1400&FORMAT=application/vnd.google-earth.kml+xml&bbox='+bottomLeftLongitude+','+bottomLeftLatitude+','+topRightLongitude+','+topRightLatitude+'&srs=CRS:84' )38 .then(response => response.text())39 .then(string => {40 const parser = new DOMParser();41 const xmlDoc = parser.parseFromString(string, 'text/xml');42 const numberOfMultiGeometry = xmlDoc.getElementsByTagName('MultiGeometry').length;43 const navigationLine = [];44 for (let index = 0; index < numberOfMultiGeometry; index++) {45 let coordinateAsString = xmlDoc.getElementsByTagName(46 'MultiGeometry')[index].getElementsByTagName(47 'LineString')[0].getElementsByTagName(48 'coordinates')[0].childNodes[0].nodeValue.split(/[ ,]+/);49 let coordinates = [];50 let innerIndex = 0;51 while (innerIndex < coordinateAsString.length ) {52 coordinates.push({53 longitude: +coordinateAsString[innerIndex],54 latitude: +coordinateAsString[innerIndex+1],55 });56 innerIndex += 257 }58 navigationLine.push({59 coordinates: coordinates60 });61 }62 isNavigationRequest = false;63 return navigationLine;64 }).65 catch(error => {66 console.log(error.message); //undefined is not a constructor (evaluating 'new window.DOMParser()')67 });68};69const updateLightBeacons = async (userLongitude, userLatitude) => {70 setURI(userLongitude, userLatitude);71 if (isBeaconRequest) {72 return fetchLightBeacons();73 } else {74 return [];75 }76}77const updateNavigationLines = async (userLongitude, userLatitude) => {78 setURI(userLongitude, userLatitude);79 if (isNavigationRequest) {80 return fetchNavigationLines();81 } else {82 return [];83 }84}85const setURI = (userLongitude, userLatitude) => {86 if (87 (userLatitude >= topRightLatitude - (LATITUDE_DELTA_FOR_LINES_AND_BEACONS / 2 )) ||88 (userLongitude >= topRightLongitude - (LONGITUDE_DELTA_FOR_LINES_AND_BEACONS / 2 )) ||89 (userLatitude <= bottomLeftLatitude - (LATITUDE_DELTA_FOR_LINES_AND_BEACONS / 2 )) ||90 (userLongitude <= bottomLeftLongitude - (LONGITUDE_DELTA_FOR_LINES_AND_BEACONS / 2 ))91 ) {92 //const lowerLeftPoint = ''+(userLongitude - LONGITUDE_DELTA_FOR_LINES_AND_BEACONS)+','+(userLatitude - LATITUDE_DELTA_FOR_LINES_AND_BEACONS)+'';93 //const upperRightPoint = ''+(userLongitude + LONGITUDE_DELTA_FOR_LINES_AND_BEACONS)+','+(userLatitude + LATITUDE_DELTA_FOR_LINES_AND_BEACONS)+'';94 //const bBoxCoordinates = ''+lowerLeftPoint+','+upperRightPoint+''95 bottomLeftLongitude = userLongitude - LONGITUDE_DELTA_FOR_LINES_AND_BEACONS;96 bottomLeftLatitude = userLatitude - LATITUDE_DELTA_FOR_LINES_AND_BEACONS;97 topRightLongitude = userLongitude + LONGITUDE_DELTA_FOR_LINES_AND_BEACONS;98 topRightLatitude = userLatitude + LATITUDE_DELTA_FOR_LINES_AND_BEACONS;99 isNavigationRequest = true;100 isBeaconRequest = true;101 }102}103export const finnshTransportService = {104 updateLightBeacons,105 updateNavigationLines...

Full Screen

Full Screen

service-worker.js

Source:service-worker.js Github

copy

Full Screen

...13 "/static/js/js.utils.js", 14 "/static/js/FileSaver/FileSaver.min.js",15 "/static/js/FileSaver/FileSaver.min.js.map",16];17function isNavigationRequest(event) {18 return event.request.mode === 'navigate';19}20function isCachedAssetRequest(event) {21 let isSameOriginRequest = event.request.url.startsWith(self.location.origin);22 let isFontRequest = FONT_ORIGINS.some((origin) => event.request.url.startsWith(origin));23 return !isNavigationRequest(event) && (isSameOriginRequest || isFontRequest);24}25function isHtmlRequest(event) {26 let isGetRequest = event.request.method === 'GET';27 let isHTMLRequest = event.request.headers.get('accept').startsWith(HTML_CONTENT_TYPE);28 return isNavigationRequest(event) || (isGetRequest && isHTMLRequest);29}30self.addEventListener('install', function(event) {31 let now = Date.now();32 event.waitUntil(33 caches.open(CACHE_NAME).then(function(cache) {34 let cachePromises = PRE_CACHED_ASSETS.map(function(asset) {35 var url = new URL(asset, location.href);36 var request = new Request(url, { mode: 'no-cors' });37 return fetch(request).then(function(response) {38 if (response.status >= 400) {39 throw new Error('prefetch failed!');40 }41 return cache.put(asset, response);42 });...

Full Screen

Full Screen

blockAds.js

Source:blockAds.js Github

copy

Full Screen

1import {URL} from 'url';2import BLOCKING from './blocking.js';3import {BLOCKED_BODY, BLOCKED_CODE, BLOCKED_HEADERS} from './blockedResponse.js';4export async function blockAds(/*zombie, sessionId*/) {5 // do nothing6}7export async function onInterceptRequest({sessionId, message}, zombie) {8 if ( message.method == "Fetch.requestPaused" ) {9 const {request:{url}, requestId, resourceType, responseErrorReason} = message.params;10 const isNavigationRequest = resourceType == "Document";11 const host = new URL(url).host;12 let blocked = false;13 for( const regex of BLOCKING ) {14 if ( regex.test(host) ) {15 try {16 if ( isNavigationRequest ) {17 // we want to provide a response body to indicate that we blocked it via an ad blocker18 await zombie.send("Fetch.fulfillRequest", {19 requestId,20 responseHeaders: BLOCKED_HEADERS,21 responseCode: BLOCKED_CODE,22 body: BLOCKED_BODY23 },24 sessionId25 );26 } else {27 await zombie.send("Fetch.failRequest", {28 requestId,29 errorReason: "BlockedByClient"30 },31 sessionId32 );33 }34 blocked = true;35 break;36 } catch(e) {37 console.warn("Issue with intercepting request", e);38 }39 }40 }41 if ( blocked ) return;42 // responseErrorReason never appears to be set, regardless of interception stage 43 //console.log({responseErrorReason,requestId, url, resourceType});44 if ( responseErrorReason ) {45 if ( isNavigationRequest ) {46 await zombie.send("Fetch.fulfillRequest", {47 requestId,48 responseHeaders: BLOCKED_HEADERS,49 responseCode: BLOCKED_CODE,50 body: Buffer.from(responseErrorReason).toString("base64"),51 },52 sessionId53 );54 } else {55 await zombie.send("Fetch.failRequest", {56 requestId,57 errorReason: responseErrorReason58 },59 sessionId60 );61 }62 } else {63 try {64 await zombie.send("Fetch.continueRequest", {65 requestId,66 },67 sessionId68 );69 } catch(e) {70 console.warn("Issue with continuing request", e);71 }72 }73 }...

Full Screen

Full Screen

LinkManager.js

Source:LinkManager.js Github

copy

Full Screen

...14 var match = message.match(/^bramble-navigate\:(.+)/);15 return match && match[1];16 }17 // Whether or not this message is a navigation request from the LinkManagerRemote script.18 function isNavigationRequest(message) {19 return !!getNavigationPath(message);20 }21 // Attempt to navigate the preview and editor to a new path22 function navigate(message) {23 var path = getNavigationPath(message);24 if(!path) {25 return;26 }27 var currentDoc = LiveDevMultiBrowser._getCurrentLiveDoc();28 if(!currentDoc) {29 return;30 }31 var currentDir = Path.dirname(currentDoc.doc.file.fullPath);32 path = Path.resolve(currentDir, path);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.setRequestInterception(true);6 page.on('request', request => {7 if (request.isNavigationRequest()) {8 console.log('navigation request');9 }10 request.continue();11 });12 await browser.close();13})();14request.isNavigationRequest()15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page.setRequestInterception(true);20 page.on('request', request => {21 if (request.isNavigationRequest()) {22 console.log('navigation request');23 }24 request.continue();25 });26 await browser.close();27})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.setRequestInterception(true);6 page.on('request', request => {7 if (request.isNavigationRequest()) {8 console.log('Navigation request to: ' + request.url());9 } else {10 console.log('Resource request to: ' + request.url());11 }12 request.continue();13 });14 await browser.close();15})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.setRequestInterception(true);6 page.on('request', request => {7 if (request.isNavigationRequest()) {8 console.log('Navigation request to: ' + request.url());9 } else {10 console.log('Resource request to: ' + request.url());11 }12 request.continue();13 });14 await browser.close();15})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.setRequestInterception(true);6 page.on('request', request => {7 if (request.isNavigationRequest()) {8 console.log("Navigation Request");9 }10 else {11 console.log("Not a Navigation Request");12 }13 request.continue();14 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 page.on('request', request => {6 console.log(request.isNavigationRequest());7 });8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({ headless: false });4 const page = await browser.newPage();5 await page.setRequestInterception(true);6 page.on('request', (request) => {7 if (request.isNavigationRequest()) {8 console.log('This is a navigation request: ' + request.url());9 request.continue();10 } else {11 console.log('This is not a navigation request: ' + request.url());12 request.abort();13 }14 });15 await page.screenshot({ path: 'google.png' });16 await browser.close();17})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page.setRequestInterception(true);7 page.on('request', async (request) => {8 if (request.isNavigationRequest()) {9 console.log('Navigation Request: ' + request.url());10 } else {11 console.log('Resource Request: ' + request.url());12 }13 request.continue();14 });15})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.setRequestInterception(true);6 page.on('request', request => {7 if (request.isNavigationRequest()) {8 console.log('Navigation request for: ' + request.url());9 }10 request.continue();11 });12 await browser.close();13})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 page.on('request', request => {7 if (request.isNavigationRequest()) {8 console.log('This is a navigation request');9 }10 else {11 console.log('This is not a navigation request');12 }13 });14})();

Full Screen

Using AI Code Generation

copy

Full Screen

1async function isNavigationRequest(page) {2 const requests = [];3 page.on('request', request => {4 requests.push(request);5 });6 const navigationRequest = requests.find(request => request.isNavigationRequest());7 console.log(navigationRequest.url());8}9async function isNavigationRequest(page) {10 const requests = [];11 page.on('request', request => {12 requests.push(request);13 });14 const navigationRequest = requests.find(request => request.isNavigationRequest());15 console.log(navigationRequest.url());16}17async function isNavigationRequest(page) {18 const requests = [];19 page.on('request', request => {20 requests.push(request);21 });22 const navigationRequest = requests.find(request => request.isNavigationRequest());23 console.log(navigationRequest.url());24}25async function isNavigationRequest(page) {26 const requests = [];27 page.on('request', request => {28 requests.push(request);29 });30 const navigationRequest = requests.find(request => request.isNavigationRequest());31 console.log(navigationRequest.url());32}33async function isNavigationRequest(page) {34 const requests = [];35 page.on('request', request => {36 requests.push(request);37 });38 const navigationRequest = requests.find(request => request.isNavigationRequest());39 console.log(navigationRequest.url());40}41async function isNavigationRequest(page) {42 const requests = [];43 page.on('request', request => {44 requests.push(request);45 });46 const navigationRequest = requests.find(request => request.isNavigationRequest());47 console.log(navigationRequest.url());48}49async function isNavigationRequest(page) {50 const requests = [];

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer 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