Best JavaScript code snippet using playwright-internal
NetworkObserver.js
Source:NetworkObserver.js
...131 this._expectingInterception = false;132 this._expectingResumedRequest = undefined; // { method, headers, postData }133 this._sentOnResponse = false;134 if (this._pageNetwork)135 appendExtraHTTPHeaders(httpChannel, this._pageNetwork.combinedExtraHTTPHeaders());136 this._responseBodyChunks = [];137 httpChannel.QueryInterface(Ci.nsITraceableChannel);138 this._originalListener = httpChannel.setNewListener(this);139 if (redirectedFrom) {140 // Listener is inherited for regular redirects, so we'd like to avoid141 // calling into previous NetworkRequest.142 this._originalListener = redirectedFrom._originalListener;143 }144 this._previousCallbacks = httpChannel.notificationCallbacks;145 httpChannel.notificationCallbacks = this;146 this.QueryInterface = ChromeUtils.generateQI([147 Ci.nsIAuthPrompt2,148 Ci.nsIAuthPromptProvider,149 Ci.nsIInterfaceRequestor,150 Ci.nsINetworkInterceptController,151 Ci.nsIStreamListener,152 ]);153 if (this.redirectedFromId) {154 // Redirects are not interceptable.155 this._sendOnRequest(false);156 }157 }158 // Public interception API.159 resume(url, method, headers, postData) {160 this._expectingResumedRequest = { method, headers, postData };161 const newUri = url ? Services.io.newURI(url) : null;162 this._interceptedChannel.resetInterceptionWithURI(newUri);163 this._interceptedChannel = undefined;164 }165 // Public interception API.166 abort(errorCode) {167 const error = errorMap[errorCode] || Cr.NS_ERROR_FAILURE;168 this._interceptedChannel.cancelInterception(error);169 this._interceptedChannel = undefined;170 }171 // Public interception API.172 fulfill(status, statusText, headers, base64body) {173 this._interceptedChannel.synthesizeStatus(status, statusText);174 for (const header of headers) {175 this._interceptedChannel.synthesizeHeader(header.name, header.value);176 if (header.name.toLowerCase() === 'set-cookie') {177 Services.cookies.QueryInterface(Ci.nsICookieService);178 Services.cookies.setCookieStringFromHttp(this.httpChannel.URI, header.value, this.httpChannel);179 }180 }181 const synthesized = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);182 synthesized.data = base64body ? atob(base64body) : '';183 this._interceptedChannel.startSynthesizedResponse(synthesized, null, null, '', false);184 this._interceptedChannel.finishSynthesizedResponse();185 this._interceptedChannel = undefined;186 }187 // Instrumentation called by NetworkObserver.188 _onInternalRedirect(newChannel) {189 // Intercepted requests produce "internal redirects" - this is both for our own190 // interception and service workers.191 // An internal redirect has the same channelId, inherits notificationCallbacks and192 // listener, and should be used instead of an old channel.193 this._networkObserver._channelToRequest.delete(this.httpChannel);194 this.httpChannel = newChannel;195 this._networkObserver._channelToRequest.set(this.httpChannel, this);196 }197 // Instrumentation called by NetworkObserver.198 _onInternalRedirectReady() {199 // Resumed request is first internally redirected to a new request,200 // and then the new request is ready to be updated.201 if (!this._expectingResumedRequest)202 return;203 const { method, headers, postData } = this._expectingResumedRequest;204 this._expectingResumedRequest = undefined;205 if (headers) {206 for (const header of requestHeaders(this.httpChannel))207 this.httpChannel.setRequestHeader(header.name, '', false /* merge */);208 for (const header of headers)209 this.httpChannel.setRequestHeader(header.name, header.value, false /* merge */);210 } else if (this._pageNetwork) {211 appendExtraHTTPHeaders(this.httpChannel, this._pageNetwork.combinedExtraHTTPHeaders());212 }213 if (method)214 this.httpChannel.requestMethod = method;215 if (postData)216 setPostData(this.httpChannel, postData, headers);217 }218 // nsIInterfaceRequestor219 getInterface(iid) {220 if (iid.equals(Ci.nsIAuthPrompt2) || iid.equals(Ci.nsIAuthPromptProvider) || iid.equals(Ci.nsINetworkInterceptController))221 return this;222 if (iid.equals(Ci.nsIAuthPrompt)) // Block nsIAuthPrompt - we want nsIAuthPrompt2 to be used instead.223 throw Cr.NS_ERROR_NO_INTERFACE;224 if (this._previousCallbacks)225 return this._previousCallbacks.getInterface(iid);226 throw Cr.NS_ERROR_NO_INTERFACE;227 }228 // nsIAuthPromptProvider229 getAuthPrompt(aPromptReason, iid) {230 return this;231 }232 // nsIAuthPrompt2233 asyncPromptAuth(aChannel, aCallback, aContext, level, authInfo) {234 let canceled = false;235 Promise.resolve().then(() => {236 if (canceled)237 return;238 const hasAuth = this.promptAuth(aChannel, level, authInfo);239 if (hasAuth)240 aCallback.onAuthAvailable(aContext, authInfo);241 else242 aCallback.onAuthCancelled(aContext, true);243 });244 return {245 QueryInterface: ChromeUtils.generateQI([Ci.nsICancelable]),246 cancel: () => {247 aCallback.onAuthCancelled(aContext, false);248 canceled = true;249 }250 };251 }252 // nsIAuthPrompt2253 promptAuth(aChannel, level, authInfo) {254 if (authInfo.flags & Ci.nsIAuthInformation.PREVIOUS_FAILED)255 return false;256 const pageNetwork = this._pageNetwork;257 if (!pageNetwork)258 return false;259 let credentials = null;260 if (authInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY) {261 const proxy = this._networkObserver._targetRegistry.getProxyInfo(aChannel);262 credentials = proxy ? {username: proxy.username, password: proxy.password} : null;263 } else {264 credentials = pageNetwork._target.browserContext().httpCredentials;265 }266 if (!credentials)267 return false;268 authInfo.username = credentials.username;269 authInfo.password = credentials.password;270 // This will produce a new request with respective auth header set.271 // It will have the same id as ours. We expect it to arrive as new request and272 // will treat it as our own redirect.273 this._networkObserver._expectRedirect(this.httpChannel.channelId + '', this);274 return true;275 }276 // nsINetworkInterceptController277 shouldPrepareForIntercept(aURI, channel) {278 const interceptController = this._fallThroughInterceptController();279 if (interceptController && interceptController.shouldPrepareForIntercept(aURI, channel)) {280 // We assume that interceptController is a service worker if there is one,281 // and yield interception to it. We are not going to intercept ourselves,282 // so we send onRequest now.283 this._sendOnRequest(false);284 return true;285 }286 if (channel !== this.httpChannel) {287 // Not our channel? Just in case this happens, don't do anything.288 return false;289 }290 // We do not want to intercept any redirects, because we are not able291 // to intercept subresource redirects, and it's unreliable for main requests.292 // We do not sendOnRequest here, because redirects do that in constructor.293 if (this.redirectedFromId)294 return false;295 const shouldIntercept = this._shouldIntercept();296 if (!shouldIntercept) {297 // We are not intercepting - ready to issue onRequest.298 this._sendOnRequest(false);299 return false;300 }301 this._expectingInterception = true;302 return true;303 }304 // nsINetworkInterceptController305 channelIntercepted(intercepted) {306 if (!this._expectingInterception) {307 // We are not intercepting, fall-through.308 const interceptController = this._fallThroughInterceptController();309 if (interceptController)310 interceptController.channelIntercepted(intercepted);311 return;312 }313 this._expectingInterception = false;314 this._interceptedChannel = intercepted.QueryInterface(Ci.nsIInterceptedChannel);315 const pageNetwork = this._pageNetwork;316 if (!pageNetwork) {317 // Just in case we disabled instrumentation while intercepting, resume and forget.318 this.resume();319 return;320 }321 const browserContext = pageNetwork._target.browserContext();322 if (browserContext.settings.onlineOverride === 'offline') {323 // Implement offline.324 this.abort(Cr.NS_ERROR_OFFLINE);325 return;326 }327 // Ok, so now we have intercepted the request, let's issue onRequest.328 // If interception has been disabled while we were intercepting, resume and forget.329 const interceptionEnabled = this._shouldIntercept();330 this._sendOnRequest(!!interceptionEnabled);331 if (interceptionEnabled)332 pageNetwork._interceptedRequests.set(this.requestId, this);333 else334 this.resume();335 }336 // nsIStreamListener337 onDataAvailable(aRequest, aInputStream, aOffset, aCount) {338 // Turns out webcompat shims might redirect to339 // SimpleChannel, so we get requests from a different channel.340 // See https://github.com/microsoft/playwright/issues/9418#issuecomment-944836244341 if (aRequest !== this.httpChannel)342 return;343 // For requests with internal redirect (e.g. intercepted by Service Worker),344 // we do not get onResponse normally, but we do get nsIStreamListener notifications.345 this._sendOnResponse(false);346 const iStream = new BinaryInputStream(aInputStream);347 const sStream = new StorageStream(8192, aCount, null);348 const oStream = new BinaryOutputStream(sStream.getOutputStream(0));349 // Copy received data as they come.350 const data = iStream.readBytes(aCount);351 this._responseBodyChunks.push(data);352 oStream.writeBytes(data, aCount);353 try {354 this._originalListener.onDataAvailable(aRequest, sStream.newInputStream(0), aOffset, aCount);355 } catch (e) {356 // Be ready to original listener exceptions.357 }358 }359 // nsIStreamListener360 onStartRequest(aRequest) {361 // Turns out webcompat shims might redirect to362 // SimpleChannel, so we get requests from a different channel.363 // See https://github.com/microsoft/playwright/issues/9418#issuecomment-944836244364 if (aRequest !== this.httpChannel)365 return;366 try {367 this._originalListener.onStartRequest(aRequest);368 } catch (e) {369 // Be ready to original listener exceptions.370 }371 }372 // nsIStreamListener373 onStopRequest(aRequest, aStatusCode) {374 // Turns out webcompat shims might redirect to375 // SimpleChannel, so we get requests from a different channel.376 // See https://github.com/microsoft/playwright/issues/9418#issuecomment-944836244377 if (aRequest !== this.httpChannel)378 return;379 try {380 this._originalListener.onStopRequest(aRequest, aStatusCode);381 } catch (e) {382 // Be ready to original listener exceptions.383 }384 if (aStatusCode === 0) {385 // For requests with internal redirect (e.g. intercepted by Service Worker),386 // we do not get onResponse normally, but we do get nsIRequestObserver notifications.387 this._sendOnResponse(false);388 const body = this._responseBodyChunks.join('');389 const pageNetwork = this._pageNetwork;390 if (pageNetwork)391 pageNetwork._responseStorage.addResponseBody(this, body);392 this._sendOnRequestFinished();393 } else {394 this._sendOnRequestFailed(aStatusCode);395 }396 delete this._responseBodyChunks;397 }398 _shouldIntercept() {399 const pageNetwork = this._pageNetwork;400 if (!pageNetwork)401 return false;402 if (pageNetwork._requestInterceptionEnabled)403 return true;404 const browserContext = pageNetwork._target.browserContext();405 if (browserContext.requestInterceptionEnabled)406 return true;407 if (browserContext.settings.onlineOverride === 'offline')408 return true;409 return false;410 }411 _fallThroughInterceptController() {412 if (!this._previousCallbacks || !(this._previousCallbacks instanceof Ci.nsINetworkInterceptController))413 return undefined;414 return this._previousCallbacks.getInterface(Ci.nsINetworkInterceptController);415 }416 _sendOnRequest(isIntercepted) {417 // Note: we call _sendOnRequest either after we intercepted the request,418 // or at the first moment we know that we are not going to intercept.419 const pageNetwork = this._pageNetwork;420 if (!pageNetwork)421 return;422 const loadInfo = this.httpChannel.loadInfo;423 const causeType = loadInfo?.externalContentPolicyType || Ci.nsIContentPolicy.TYPE_OTHER;424 const internalCauseType = loadInfo?.internalContentPolicyType || Ci.nsIContentPolicy.TYPE_OTHER;425 pageNetwork.emit(PageNetwork.Events.Request, {426 url: this.httpChannel.URI.spec,427 frameId: this._frameId,428 isIntercepted,429 requestId: this.requestId,430 redirectedFrom: this.redirectedFromId,431 postData: readRequestPostData(this.httpChannel),432 headers: requestHeaders(this.httpChannel),433 method: this.httpChannel.requestMethod,434 navigationId: this.navigationId,435 cause: causeTypeToString(causeType),436 internalCause: causeTypeToString(internalCauseType),437 }, this._frameId);438 }439 _sendOnResponse(fromCache, opt_statusCode, opt_statusText) {440 if (this._sentOnResponse) {441 // We can come here twice because of internal redirects, e.g. service workers.442 return;443 }444 this._sentOnResponse = true;445 const pageNetwork = this._pageNetwork;446 if (!pageNetwork)447 return;448 this.httpChannel.QueryInterface(Ci.nsIHttpChannelInternal);449 this.httpChannel.QueryInterface(Ci.nsITimedChannel);450 const timing = {451 startTime: this.httpChannel.channelCreationTime,452 domainLookupStart: this.httpChannel.domainLookupStartTime,453 domainLookupEnd: this.httpChannel.domainLookupEndTime,454 connectStart: this.httpChannel.connectStartTime,455 secureConnectionStart: this.httpChannel.secureConnectionStartTime,456 connectEnd: this.httpChannel.connectEndTime,457 requestStart: this.httpChannel.requestStartTime,458 responseStart: this.httpChannel.responseStartTime,459 };460 const { status, statusText, headers } = responseHead(this.httpChannel, opt_statusCode, opt_statusText);461 let remoteIPAddress = undefined;462 let remotePort = undefined;463 try {464 remoteIPAddress = this.httpChannel.remoteAddress;465 remotePort = this.httpChannel.remotePort;466 } catch (e) {467 // remoteAddress is not defined for cached requests.468 }469 pageNetwork.emit(PageNetwork.Events.Response, {470 requestId: this.requestId,471 securityDetails: getSecurityDetails(this.httpChannel),472 fromCache,473 headers,474 remoteIPAddress,475 remotePort,476 status,477 statusText,478 timing,479 }, this._frameId);480 }481 _sendOnRequestFailed(error) {482 const pageNetwork = this._pageNetwork;483 if (pageNetwork) {484 pageNetwork.emit(PageNetwork.Events.RequestFailed, {485 requestId: this.requestId,486 errorCode: helper.getNetworkErrorStatusText(error),487 }, this._frameId);488 }489 this._networkObserver._channelToRequest.delete(this.httpChannel);490 }491 _sendOnRequestFinished() {492 const pageNetwork = this._pageNetwork;493 if (pageNetwork) {494 let protocolVersion = undefined;495 try {496 protocolVersion = this.httpChannel.protocolVersion;497 } catch (e) {498 // protocolVersion is unavailable in certain cases.499 };500 pageNetwork.emit(PageNetwork.Events.RequestFinished, {501 requestId: this.requestId,502 responseEndTime: this.httpChannel.responseEndTime,503 transferSize: this.httpChannel.transferSize,504 encodedBodySize: this.httpChannel.encodedBodySize,505 protocolVersion,506 }, this._frameId);507 }508 this._networkObserver._channelToRequest.delete(this.httpChannel);509 }510}511class NetworkObserver {512 static instance() {513 return NetworkObserver._instance || null;514 }515 constructor(targetRegistry) {516 EventEmitter.decorate(this);517 NetworkObserver._instance = this;518 this._targetRegistry = targetRegistry;519 this._channelToRequest = new Map(); // http channel -> network request520 this._expectedRedirect = new Map(); // expected redirect channel id (string) -> network request521 const protocolProxyService = Cc['@mozilla.org/network/protocol-proxy-service;1'].getService();522 this._channelProxyFilter = {523 QueryInterface: ChromeUtils.generateQI([Ci.nsIProtocolProxyChannelFilter]),524 applyFilter: (channel, defaultProxyInfo, proxyFilter) => {525 const proxy = this._targetRegistry.getProxyInfo(channel);526 if (!proxy) {527 proxyFilter.onProxyFilterResult(defaultProxyInfo);528 return;529 }530 proxyFilter.onProxyFilterResult(protocolProxyService.newProxyInfo(531 proxy.type,532 proxy.host,533 proxy.port,534 '', /* aProxyAuthorizationHeader */535 '', /* aConnectionIsolationKey */536 Ci.nsIProxyInfo.TRANSPARENT_PROXY_RESOLVES_HOST, /* aFlags */537 UINT32_MAX, /* aFailoverTimeout */538 null, /* failover proxy */539 ));540 },541 };542 protocolProxyService.registerChannelFilter(this._channelProxyFilter, 0 /* position */);543 this._channelSink = {544 QueryInterface: ChromeUtils.generateQI([Ci.nsIChannelEventSink]),545 asyncOnChannelRedirect: (oldChannel, newChannel, flags, callback) => {546 this._onRedirect(oldChannel, newChannel, flags);547 callback.onRedirectVerifyCallback(Cr.NS_OK);548 },549 };550 this._channelSinkFactory = {551 QueryInterface: ChromeUtils.generateQI([Ci.nsIFactory]),552 createInstance: (aOuter, aIID) => this._channelSink.QueryInterface(aIID),553 };554 // Register self as ChannelEventSink to track redirects.555 const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);556 registrar.registerFactory(SINK_CLASS_ID, SINK_CLASS_DESCRIPTION, SINK_CONTRACT_ID, this._channelSinkFactory);557 Services.catMan.addCategoryEntry(SINK_CATEGORY_NAME, SINK_CONTRACT_ID, SINK_CONTRACT_ID, false, true);558 this._eventListeners = [559 helper.addObserver(this._onRequest.bind(this), 'http-on-modify-request'),560 helper.addObserver(this._onResponse.bind(this, false /* fromCache */), 'http-on-examine-response'),561 helper.addObserver(this._onResponse.bind(this, true /* fromCache */), 'http-on-examine-cached-response'),562 helper.addObserver(this._onResponse.bind(this, true /* fromCache */), 'http-on-examine-merged-response'),563 ];564 }565 _expectRedirect(channelId, previous) {566 this._expectedRedirect.set(channelId, previous);567 }568 _onRedirect(oldChannel, newChannel, flags) {569 if (!(oldChannel instanceof Ci.nsIHttpChannel) || !(newChannel instanceof Ci.nsIHttpChannel))570 return;571 const oldHttpChannel = oldChannel.QueryInterface(Ci.nsIHttpChannel);572 const newHttpChannel = newChannel.QueryInterface(Ci.nsIHttpChannel);573 const request = this._channelToRequest.get(oldHttpChannel);574 if (flags & Ci.nsIChannelEventSink.REDIRECT_INTERNAL) {575 if (request)576 request._onInternalRedirect(newHttpChannel);577 } else if (flags & Ci.nsIChannelEventSink.REDIRECT_STS_UPGRADE) {578 if (request) {579 // This is an internal HSTS upgrade. The original http request is canceled, and a new580 // equivalent https request is sent. We forge 307 redirect to follow Chromium here:581 // https://source.chromium.org/chromium/chromium/src/+/main:net/url_request/url_request_http_job.cc;l=211582 request._sendOnResponse(false, 307, 'Temporary Redirect');583 this._expectRedirect(newHttpChannel.channelId + '', request);584 }585 } else {586 if (request)587 this._expectRedirect(newHttpChannel.channelId + '', request);588 }589 }590 _findPageNetwork(httpChannel) {591 let loadContext = helper.getLoadContext(httpChannel);592 if (!loadContext)593 return;594 const target = this._targetRegistry.targetForBrowser(loadContext.topFrameElement);595 if (!target)596 return;597 return PageNetwork.forPageTarget(target);598 }599 _onRequest(channel, topic) {600 if (!(channel instanceof Ci.nsIHttpChannel))601 return;602 const httpChannel = channel.QueryInterface(Ci.nsIHttpChannel);603 const channelId = httpChannel.channelId + '';604 const redirectedFrom = this._expectedRedirect.get(channelId);605 if (redirectedFrom) {606 this._expectedRedirect.delete(channelId);607 new NetworkRequest(this, httpChannel, redirectedFrom);608 } else {609 const redirectedRequest = this._channelToRequest.get(httpChannel);610 if (redirectedRequest)611 redirectedRequest._onInternalRedirectReady();612 else613 new NetworkRequest(this, httpChannel);614 }615 }616 _onResponse(fromCache, httpChannel, topic) {617 const request = this._channelToRequest.get(httpChannel);618 if (request)619 request._sendOnResponse(fromCache);620 }621 dispose() {622 this._activityDistributor.removeObserver(this);623 const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);624 registrar.unregisterFactory(SINK_CLASS_ID, this._channelSinkFactory);625 Services.catMan.deleteCategoryEntry(SINK_CATEGORY_NAME, SINK_CONTRACT_ID, false);626 helper.removeListeners(this._eventListeners);627 }628}629const protocolVersionNames = {630 [Ci.nsITransportSecurityInfo.TLS_VERSION_1]: 'TLS 1',631 [Ci.nsITransportSecurityInfo.TLS_VERSION_1_1]: 'TLS 1.1',632 [Ci.nsITransportSecurityInfo.TLS_VERSION_1_2]: 'TLS 1.2',633 [Ci.nsITransportSecurityInfo.TLS_VERSION_1_3]: 'TLS 1.3',634};635function getSecurityDetails(httpChannel) {636 const securityInfo = httpChannel.securityInfo;637 if (!securityInfo)638 return null;639 securityInfo.QueryInterface(Ci.nsITransportSecurityInfo);640 if (!securityInfo.serverCert)641 return null;642 return {643 protocol: protocolVersionNames[securityInfo.protocolVersion] || '<unknown>',644 subjectName: securityInfo.serverCert.commonName,645 issuer: securityInfo.serverCert.issuerCommonName,646 // Convert to seconds.647 validFrom: securityInfo.serverCert.validity.notBefore / 1000 / 1000,648 validTo: securityInfo.serverCert.validity.notAfter / 1000 / 1000,649 };650}651function readRequestPostData(httpChannel) {652 if (!(httpChannel instanceof Ci.nsIUploadChannel))653 return undefined;654 let iStream = httpChannel.uploadStream;655 if (!iStream)656 return undefined;657 const isSeekableStream = iStream instanceof Ci.nsISeekableStream;658 // For some reason, we cannot rewind back big streams,659 // so instead we should clone them.660 const isCloneable = iStream instanceof Ci.nsICloneableInputStream;661 if (isCloneable)662 iStream = iStream.clone();663 let prevOffset;664 if (isSeekableStream) {665 prevOffset = iStream.tell();666 iStream.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);667 }668 // Read data from the stream.669 let result = undefined;670 try {671 const buffer = NetUtil.readInputStream(iStream, iStream.available());672 const bytes = new Uint8Array(buffer);673 let binary = '';674 for (let i = 0; i < bytes.byteLength; i++)675 binary += String.fromCharCode(bytes[i]);676 result = btoa(binary);677 } catch (err) {678 result = '';679 }680 // Seek locks the file, so seek to the beginning only if necko hasn't681 // read it yet, since necko doesn't seek to 0 before reading (at lest682 // not till 459384 is fixed).683 if (isSeekableStream && prevOffset == 0 && !isCloneable)684 iStream.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);685 return result;686}687function requestHeaders(httpChannel) {688 const headers = [];689 httpChannel.visitRequestHeaders({690 visitHeader: (name, value) => headers.push({name, value}),691 });692 return headers;693}694function causeTypeToString(causeType) {695 for (let key in Ci.nsIContentPolicy) {696 if (Ci.nsIContentPolicy[key] === causeType)697 return key;698 }699 return 'TYPE_OTHER';700}701function appendExtraHTTPHeaders(httpChannel, headers) {702 if (!headers)703 return;704 for (const header of headers)705 httpChannel.setRequestHeader(header.name, header.value, false /* merge */);706}707class ResponseStorage {708 constructor(maxTotalSize, maxResponseSize) {709 this._totalSize = 0;710 this._maxResponseSize = maxResponseSize;711 this._maxTotalSize = maxTotalSize;712 this._responses = new Map();713 }714 addResponseBody(request, body) {715 if (body.length > this._maxResponseSize) {...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 for (const browserType of ['chromium', 'firefox', 'webkit']) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 await context.addInitScript(() => {7 window.playwright = {8 appendExtraHTTPHeaders: (headers) => {9 window.__extraHeaders = headers;10 },11 };12 });13 const page = await context.newPage();14 await page.evaluate(() => {15 window.playwright.appendExtraHTTPHeaders({16 });17 });18 await browser.close();19 }20})();21{22 "headers": {23 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",24 "Accept-Language": "en-US,en;q=0.9",25 "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/85.0.4183.0 Safari/537.36",26 }27}28{29 "headers": {30 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",31 "Accept-Language": "en-US,en;q=0.5",
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.route('**', route => {6 route.continue({7 headers: {8 },9 });10 });11 await browser.close();12})();13User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4298.0 Safari/537.3614Accept-Language: en-US,en;q=0.9,es;q=0.8
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext({5 extraHTTPHeaders: {6 },7 });8 const page = await context.newPage();9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 await context.appendExtraHTTPHeaders({17 });18 const page = await context.newPage();19 await page.screenshot({ path: `example.png` });20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 await context.appendExtraHTTPHeaders({27 });28 const page = await context.newPage();29 await page.screenshot({ path: `example.png` });30 await browser.close();31})();32const { chromium } = require('playwright');33(async () => {34 const browser = await chromium.launch();35 const context = await browser.newContext();36 await context.appendExtraHTTPHeaders({37 });38 const page = await context.newPage();39 await page.screenshot({ path: `example.png` });40 await browser.close();41})();42const { chromium } = require('playwright');43(async () => {44 const browser = await chromium.launch();45 const context = await browser.newContext();46 await context.appendExtraHTTPHeaders({47 });48 const page = await context.newPage();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 context._browser._connection.send('Network.setExtraHTTPHeaders', {6 headers: { 'X-Test': 'test' }7 });8 const page = await context.newPage();9 await page.screenshot({ path: 'headers.png' });10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 context._browser._connection.send('Network.setExtraHTTPHeaders', {17 headers: { 'X-Test': 'test' }18 });19 const page = await context.newPage();20 await page.screenshot({ path: 'headers2.png' });21 await browser.close();22})();23const { chromium } = require('playwright');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext();27 context._browser._connection.send('Network.setExtraHTTPHeaders', {28 headers: { 'X-Test': 'test' }29 });30 const page = await context.newPage();31 await page.screenshot({ path: 'headers3.png' });32 await browser.close();33})();34const { chromium } = require('playwright');35(async () => {36 const browser = await chromium.launch();37 const context = await browser.newContext();38 context._browser._connection.send('Network.setExtraHTTPHeaders', {39 headers: { 'X-Test': 'test' }40 });41 const page = await context.newPage();42 await page.screenshot({ path: 'headers4.png' });43 await browser.close();44})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 extraHTTPHeaders: {5 },6 });7 const context = await browser.newContext();8 await context.appendExtraHTTPHeaders({9 });10 const page = await context.newPage();11 await page.close();12 await context.close();13 await browser.close();14})();15{16 "headers": {17 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36",18 }19}
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3const context = await browser.newContext({ ignoreHTTPSErrors: true });4await context['setExtraHTTPHeaders']({ 'x-custom-header': 'value' });5const page = await context.newPage();6await browser.close();7})();8const playwright = require('playwright');9(async () => {10const context = await browser.newContext({ ignoreHTTPSErrors: true });11await context.addInitScript(() => {12window['playwright'] = {13setExtraHTTPHeaders: (headers) => {14window['playwrightState'].extraHTTPHeaders = headers;15}16};17});18await context.addInitScript(() => {19window['playwright'].setExtraHTTPHeaders({ 'x-custom-header': 'value' });20});21const page = await context.newPage();22await browser.close();23})();
Using AI Code Generation
1const { chromium } = require('playwright');2const { InternalRequest } = require('playwright/lib/server/network');3const { URL } = require('url');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const request = new InternalRequest(page, url, 'GET', null, null);9 request.appendExtraHTTPHeaders({ 'X-Test-Header': 'test' });10 console.log(request.headers());11 await browser.close();12})();13import { chromium } from 'playwright';14import { InternalRequest } from 'playwright/lib/server/network';15import { URL } from 'url';16(async () => {17 const browser = await chromium.launch();18 const context = await browser.newContext();19 const page = await context.newPage();20 const request = new InternalRequest(page, url, 'GET', null, null);21 request.appendExtraHTTPHeaders({ 'X-Test-Header': 'test' });22 console.log(request.headers());23 await browser.close();24})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 extraHTTPHeaders: {5 }6 });7 const context = await browser.newContext();8 const page = await context.newPage();9 await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch({14 });15 const context = await browser.newContext({16 extraHTTPHeaders: {17 }18 });19 const page = await context.newPage();20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch({25 });26 const context = await browser.newContext();27 const page = await context.newPage({28 extraHTTPHeaders: {29 }30 });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch({36 });37 const context = await browser.newContext({38 extraHTTPHeaders: {39 }40 });41 const page = await context.newPage();42 await browser.close();43})();44const { chromium } = require('playwright');45(async () => {46 const browser = await chromium.launch({47 });48 const context = await browser.newContext({49 extraHTTPHeaders: {50 }51 });52 const page = await context.newPage({53 extraHTTPHeaders: {
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const page = await browser.newPage();5 await page.route('**/*', route => {6 route.continue({7 headers: {8 }9 });10 });11 await browser.close();12})();13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch({ headless: false });16 const page = await browser.newPage();17 await page.route('**/*', route => {18 route.continue({19 headers: {20 }21 });22 });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch({ headless: false });28 const page = await browser.newPage();29 await page.route('**/*', route => {30 route.continue({31 headers: {32 }33 });34 });35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch({ headless: false });40 const page = await browser.newPage();41 await page.route('**/*', route => {42 route.continue({43 headers: {44 }45 });46 });47 await browser.close();48})();
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!!