Best JavaScript code snippet using playwright-internal
net.js
Source:net.js
1'use strict'2const url = require('url')3const { EventEmitter } = require('events')4const { Readable } = require('stream')5const { app } = require('electron')6const { Session } = process.atomBinding('session')7const { net, Net } = process.atomBinding('net')8const { URLRequest } = net9// Net is an EventEmitter.10Object.setPrototypeOf(Net.prototype, EventEmitter.prototype)11EventEmitter.call(net)12Object.setPrototypeOf(URLRequest.prototype, EventEmitter.prototype)13const kSupportedProtocols = new Set(['http:', 'https:'])14class IncomingMessage extends Readable {15 constructor (urlRequest) {16 super()17 this.urlRequest = urlRequest18 this.shouldPush = false19 this.data = []20 this.urlRequest.on('data', (event, chunk) => {21 this._storeInternalData(chunk)22 this._pushInternalData()23 })24 this.urlRequest.on('end', () => {25 this._storeInternalData(null)26 this._pushInternalData()27 })28 }29 get statusCode () {30 return this.urlRequest.statusCode31 }32 get statusMessage () {33 return this.urlRequest.statusMessage34 }35 get headers () {36 return this.urlRequest.rawResponseHeaders37 }38 get httpVersion () {39 return `${this.httpVersionMajor}.${this.httpVersionMinor}`40 }41 get httpVersionMajor () {42 return this.urlRequest.httpVersionMajor43 }44 get httpVersionMinor () {45 return this.urlRequest.httpVersionMinor46 }47 get rawTrailers () {48 throw new Error('HTTP trailers are not supported.')49 }50 get trailers () {51 throw new Error('HTTP trailers are not supported.')52 }53 _storeInternalData (chunk) {54 this.data.push(chunk)55 }56 _pushInternalData () {57 while (this.shouldPush && this.data.length > 0) {58 const chunk = this.data.shift()59 this.shouldPush = this.push(chunk)60 }61 }62 _read () {63 this.shouldPush = true64 this._pushInternalData()65 }66}67URLRequest.prototype._emitRequestEvent = function (isAsync, ...rest) {68 if (isAsync) {69 process.nextTick(() => {70 this.clientRequest.emit(...rest)71 })72 } else {73 this.clientRequest.emit(...rest)74 }75}76URLRequest.prototype._emitResponseEvent = function (isAsync, ...rest) {77 if (isAsync) {78 process.nextTick(() => {79 this._response.emit(...rest)80 })81 } else {82 this._response.emit(...rest)83 }84}85class ClientRequest extends EventEmitter {86 constructor (options, callback) {87 super()88 if (!app.isReady()) {89 throw new Error('net module can only be used after app is ready')90 }91 if (typeof options === 'string') {92 options = url.parse(options)93 } else {94 options = Object.assign({}, options)95 }96 const method = (options.method || 'GET').toUpperCase()97 let urlStr = options.url98 if (!urlStr) {99 const urlObj = {}100 const protocol = options.protocol || 'http:'101 if (!kSupportedProtocols.has(protocol)) {102 throw new Error('Protocol "' + protocol + '" not supported. ')103 }104 urlObj.protocol = protocol105 if (options.host) {106 urlObj.host = options.host107 } else {108 if (options.hostname) {109 urlObj.hostname = options.hostname110 } else {111 urlObj.hostname = 'localhost'112 }113 if (options.port) {114 urlObj.port = options.port115 }116 }117 if (options.path && / /.test(options.path)) {118 // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/119 // with an additional rule for ignoring percentage-escaped characters120 // but that's a) hard to capture in a regular expression that performs121 // well, and b) possibly too restrictive for real-world usage. That's122 // why it only scans for spaces because those are guaranteed to create123 // an invalid request.124 throw new TypeError('Request path contains unescaped characters.')125 }126 const pathObj = url.parse(options.path || '/')127 urlObj.pathname = pathObj.pathname128 urlObj.search = pathObj.search129 urlObj.hash = pathObj.hash130 urlStr = url.format(urlObj)131 }132 const redirectPolicy = options.redirect || 'follow'133 if (!['follow', 'error', 'manual'].includes(redirectPolicy)) {134 throw new Error('redirect mode should be one of follow, error or manual')135 }136 const urlRequestOptions = {137 method: method,138 url: urlStr,139 redirect: redirectPolicy140 }141 if (options.session) {142 if (options.session instanceof Session) {143 urlRequestOptions.session = options.session144 } else {145 throw new TypeError('`session` should be an instance of the Session class.')146 }147 } else if (options.partition) {148 if (typeof options.partition === 'string') {149 urlRequestOptions.partition = options.partition150 } else {151 throw new TypeError('`partition` should be an a string.')152 }153 }154 const urlRequest = new URLRequest(urlRequestOptions)155 // Set back and forward links.156 this.urlRequest = urlRequest157 urlRequest.clientRequest = this158 // This is a copy of the extra headers structure held by the native159 // net::URLRequest. The main reason is to keep the getHeader API synchronous160 // after the request starts.161 this.extraHeaders = {}162 if (options.headers) {163 for (const key in options.headers) {164 this.setHeader(key, options.headers[key])165 }166 }167 // Set when the request uses chunked encoding. Can be switched168 // to true only once and never set back to false.169 this.chunkedEncodingEnabled = false170 urlRequest.on('response', () => {171 const response = new IncomingMessage(urlRequest)172 urlRequest._response = response173 this.emit('response', response)174 })175 urlRequest.on('login', (event, authInfo, callback) => {176 this.emit('login', authInfo, (username, password) => {177 // If null or undefined username/password, force to empty string.178 if (username === null || username === undefined) {179 username = ''180 }181 if (typeof username !== 'string') {182 throw new Error('username must be a string')183 }184 if (password === null || password === undefined) {185 password = ''186 }187 if (typeof password !== 'string') {188 throw new Error('password must be a string')189 }190 callback(username, password)191 })192 })193 if (callback) {194 this.once('response', callback)195 }196 }197 get chunkedEncoding () {198 return this.chunkedEncodingEnabled199 }200 set chunkedEncoding (value) {201 if (!this.urlRequest.notStarted) {202 throw new Error('Can\'t set the transfer encoding, headers have been sent.')203 }204 this.chunkedEncodingEnabled = value205 }206 setHeader (name, value) {207 if (typeof name !== 'string') {208 throw new TypeError('`name` should be a string in setHeader(name, value).')209 }210 if (value == null) {211 throw new Error('`value` required in setHeader("' + name + '", value).')212 }213 if (!this.urlRequest.notStarted) {214 throw new Error('Can\'t set headers after they are sent.')215 }216 const key = name.toLowerCase()217 this.extraHeaders[key] = value218 this.urlRequest.setExtraHeader(name, value.toString())219 }220 getHeader (name) {221 if (name == null) {222 throw new Error('`name` is required for getHeader(name).')223 }224 if (!this.extraHeaders) {225 return226 }227 const key = name.toLowerCase()228 return this.extraHeaders[key]229 }230 removeHeader (name) {231 if (name == null) {232 throw new Error('`name` is required for removeHeader(name).')233 }234 if (!this.urlRequest.notStarted) {235 throw new Error('Can\'t remove headers after they are sent.')236 }237 const key = name.toLowerCase()238 delete this.extraHeaders[key]239 this.urlRequest.removeExtraHeader(name)240 }241 _write (chunk, encoding, callback, isLast) {242 const chunkIsString = typeof chunk === 'string'243 const chunkIsBuffer = chunk instanceof Buffer244 if (!chunkIsString && !chunkIsBuffer) {245 throw new TypeError('First argument must be a string or Buffer.')246 }247 if (chunkIsString) {248 // We convert all strings into binary buffers.249 chunk = Buffer.from(chunk, encoding)250 }251 // Since writing to the network is asynchronous, we conservatively252 // assume that request headers are written after delivering the first253 // buffer to the network IO thread.254 if (this.urlRequest.notStarted) {255 this.urlRequest.setChunkedUpload(this.chunkedEncoding)256 }257 // Headers are assumed to be sent on first call to _writeBuffer,258 // i.e. after the first call to write or end.259 const result = this.urlRequest.write(chunk, isLast)260 // The write callback is fired asynchronously to mimic Node.js.261 if (callback) {262 process.nextTick(callback)263 }264 return result265 }266 write (data, encoding, callback) {267 if (this.urlRequest.finished) {268 const error = new Error('Write after end.')269 process.nextTick(writeAfterEndNT, this, error, callback)270 return true271 }272 return this._write(data, encoding, callback, false)273 }274 end (data, encoding, callback) {275 if (this.urlRequest.finished) {276 return false277 }278 if (typeof data === 'function') {279 callback = data280 encoding = null281 data = null282 } else if (typeof encoding === 'function') {283 callback = encoding284 encoding = null285 }286 data = data || ''287 return this._write(data, encoding, callback, true)288 }289 followRedirect () {290 this.urlRequest.followRedirect()291 }292 abort () {293 this.urlRequest.cancel()294 }295 getUploadProgress () {296 return this.urlRequest.getUploadProgress()297 }298}299function writeAfterEndNT (self, error, callback) {300 self.emit('error', error)301 if (callback) callback(error)302}303Net.prototype.request = function (options, callback) {304 return new ClientRequest(options, callback)305}306net.ClientRequest = ClientRequest...
EventCollection.js
Source:EventCollection.js
1import { filter, last, first } from 'lodash';2export default class EventCollection {3 constructor(events) {4 this.events = events;5 this.cachedIdleDom = false;6 this.cachedStaticDom = false;7 this.cacheFetchedStaticDom = false;8 this.cacheDomContentLoadedDom = false;9 10 this.does_domain_have_gsc_access = null;11 }12 events() {13 return this.events.slice();14 }15 eventsOfType(type) {16 return filter(this.events, e => e.event === type);17 }18 lastEventOfType(type) {19 return last(this.eventsOfType(type));20 }21 firstEventOfType(type) {22 return first(this.eventsOfType(type));23 }24 25 documentIdleEvent() {26 let event = this.lastEventOfType('documentIdle');27 if (event && event.html) {28 const document = (new DOMParser()).parseFromString(event.html, 'text/html');29 this.cachedIdleDom = document;30 event = Object.assign(event, { document });31 }32 return event;33 }34 /*35 robotsTxtEvent() {36 let event = this.lastEventOfType('robotstxt');37 return event;38 }39 */40 getChromeLoadTimes() {41 throw new Error('getChromeLoadTimes() was removed from the API since the underlaying chrome.loadTimes() was deprecated. Instead use <a href="https://developers.google.com/web/updates/2017/12/chrome-loadtimes-deprecated" target="_blank">standardized APIs</a>.');42 }43 windowPerformanceEvent()44 {45 let event = this.lastEventOfType('windowPerformance');46 return event;47 }48 getWindowPerformance() {49 let e = this.windowPerformanceEvent().snapshot;50 return e;51 }52 getWindowPerformanceTiming() {53 let e = this.getWindowPerformance();54 return e.performance.timing;55 }56 getWindowPerformanceNavigation() {57 let e = this.getWindowPerformance();58 return e.navigation[0];59 }60 getWindowPerformancePaint() {61 let e = this.getWindowPerformance();62 return e.paint;63 }64 windowPerformanceNavigationTimingEvent()65 {66 let event = this.lastEventOfType('windowPerformanceNavigationTiming');67 return event;68 }69 getWindowPerformanceNavigationTiming() {70 return this.windowPerformanceEvent().snapshot;71 }72 documentEndEvent() {73 let event = this.lastEventOfType('documentEnd');74 if (event && event.html) {75 const document = (new DOMParser()).parseFromString(event.html, 'text/html');76 this.cachedStaticDom = document;77 event = Object.assign(event, { document });78 }79 return event;80 }81 domContentLoadedEvent() {82 let event = this.lastEventOfType('DOMContentLoaded');83 if (event && event.html) {84 const document = (new DOMParser()).parseFromString(event.html, 'text/html');85 this.cacheDomContentLoadedDom = document;86 event = Object.assign(event, { document });87 }88 return event;89 }90 fetchEvent() {91 let event = this.lastEventOfType('fetch');92 if (event && event.html) {93 const document = (new DOMParser()).parseFromString(event.html, 'text/html');94 this.cacheFetchedStaticDom = document;95 event = Object.assign(event, { document });96 }97 return event;98 }99 // helper function to get the static HTML Dom100 getStaticDom() {101 if(this.cachedStaticDom) { return this.cachedStaticDom;}102 const e = this.documentEndEvent();103 //const e = this.domContentLoadedEvent();104 //const e = this.fetchEvent(); //sadly the fetch event is not relieable enough105 return e && e.document;106 }107 getDocumentEndDom () {108 return getStaticDom();109 }110 getFetchedStaticDom() {111 if(this.cacheFetchedStaticDom){return this.cacheFetchedStaticDom; }112 const e = this.fetchEvent();113 return e && e.document;114 }115 getDomContentLoadedDom() {116 if(this.cacheDomContentLoadedDom){return this.cDomContentLoadedDom; }117 const e = this.domContentLoadedEvent();118 return e && e.document;119 }120 getFetchedDom() {121 return getFetchedStaticDom();122 }123 getIdleDom() {124 if(this.cachedIdleDom) { return this.cachedIdleDom;}125 const e = this.documentIdleEvent();126 return e && e.document;127 }128 // function to get the current live DOM129 //getLiveDom() {130 // return null;131 //}132 getHttpHeaders(what) {133 if(what==="last")134 {135 var onHeadersReceivedEvent = this.lastEventOfType('onHeadersReceived');136 }137 else {138 var onHeadersReceivedEvent = this.firstEventOfType('onHeadersReceived');139 }140 if (!onHeadersReceivedEvent) { return false; }141 var { responseHeaders } = onHeadersReceivedEvent;142 return responseHeaders;143 }144 getRawHttpHeaders(what) {145 if(what==="last")146 {147 var onHeadersReceivedEvent = this.lastEventOfType('onHeadersReceived');148 }149 else {150 var onHeadersReceivedEvent = this.firstEventOfType('onHeadersReceived');151 }152 if (!onHeadersReceivedEvent) { return false; }153 var { rawResponseHeaders } = onHeadersReceivedEvent;154 return rawResponseHeaders;155 }156 getStatusCode(what) {157 if(what==="last")158 {159 var onHeadersReceivedEvent = this.lastEventOfType('onHeadersReceived');160 }161 else {162 var onHeadersReceivedEvent = this.firstEventOfType('onHeadersReceived');163 }164 if (!onHeadersReceivedEvent) { return false; }165 let { statusCode } = onHeadersReceivedEvent;166 let headers = onHeadersReceivedEvent.responseHeaders;167 let real_statuscode = parseInt(headers['status'],10);168 if(real_statuscode>99&&real_statuscode<600)169 {170 return real_statuscode;171 }172 return statusCode;173 }174 getLocation(where = 'idle') {175 if (where === 'static')176 {177 var e = this.documentEndEvent();178 return e.location;179 }180 else {181 //if (where === 'idle') {182 var e = this.documentIdleEvent();183 return e.location;184 }185 }186 getURL(what) {187 let events = this.events;188 let url = undefined;189 //first190 if(what === "last")191 {192 let reverse_e = events.slice(0).reverse();193 for (let e of reverse_e)194 {195 url = e.url;196 if (url) { break; }197 /* url = e.location.href;198 if (url) {break} */199 }200 }201 else //if (what==="first")202 {203 for (let e of events)204 {205 url = e.url;206 if (url) { break; }207 /* url = e.location.href;208 if (url) {break} */209 }210 }211 return url;212 }213 getUrl(what) { return getURL(what); }214 //TODO215 //getProtokoll216 hasGscAccess = (token, hasF, noF) =>217 {218 219 if(this.does_domain_have_gsc_access === true)220 {221 222 hasF();return true;223 }224 if(this.does_domain_have_gsc_access === false)225 {226 227 noF(); return false;228 }229 230 if(!token){noF();return false;};231 let url = this.getURL();232 let uo = new URL(url);233 let origin = uo.origin+'/';234 let api = 'https://www.googleapis.com/webmasters/v3/sites/'+encodeURIComponent(origin);235 const headers = {236 Authorization: `Bearer ${token}`,237 };238 fetch(api, { headers }).then((response)=>{239 240 if(response.status!==200)241 {242 243 244 response.clone().json().then((data)=>{245 246 247 248 noF();249 this.does_domain_have_gsc_access = false;250 return false;251 });252 } else253 {254 255 256 response.clone().json().then((data)=>{257 258 259 260 hasF();261 this.does_domain_have_gsc_access = true;262 return true;263 });264 }265 266 267 }).catch((err)=>{268 noF();269 this.does_domain_have_gsc_access = false;270 return false;271 });272 return null;273 }...
capture.js
Source:capture.js
1/**2 * Created by Xingheng on 1/31/17.3 */4import { _, console_with_prefix } from './utils'; // eslint-disable-line camelcase5import { attemptParseBuffer, attemptParseText } from './parsers';6var logger = console_with_prefix('capture');7var HTTP_PROTOCOL = (('http:' === (document && document.location.protocol)) ? 'http://' : 'https://');8function handleRequestFinished(xhrInstance, postData, recorder) {9 logger.log('processResponse for' + xhrInstance._url);10 var endTime = (new Date()).toISOString();11 if (recorder) {12 // avoid apiRequest.io and moesif.com13 var myUrl = xhrInstance._url ? xhrInstance._url.toLowerCase() : xhrInstance._url;14 if(myUrl && myUrl.indexOf('moesif.com') < 0 && myUrl.indexOf('apirequest.io') < 0) {15 var requestModel = {16 'uri': convertToFullUrl(xhrInstance._url),17 'verb': xhrInstance._method,18 'time': xhrInstance._startTime,19 'headers': xhrInstance._requestHeaders20 };21 if (postData) {22 if (typeof postData === 'string') {23 logger.log('request post data is string');24 logger.log(postData);25 var parseResult = attemptParseText(postData);26 requestModel['transfer_encoding'] = parseResult['transfer_encoding'];27 requestModel['body'] = parseResult['body'];28 } else if (typeof postData === 'object' || Array.isArray(postData) || typeof postData === 'number' || typeof postData === 'boolean') {29 requestModel['body'] = postData;30 }31 }32 var rawResponseHeaders = xhrInstance.getAllResponseHeaders();33 logger.log('rawResponseHeaders are ' + rawResponseHeaders);34 var responseHeaders = parseResponseHeaders(rawResponseHeaders);35 var _status = xhrInstance.status;36 // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request37 if (_status === 1223) {38 _status = 204;39 }40 var responseModel = {41 'status': _status,42 'time': endTime,43 'headers': responseHeaders44 };45 logger.log('responseType: ' + xhrInstance.responseType);46 logger.log('responseText: ' + xhrInstance.responseText);47 logger.log('response: ' + xhrInstance.response);48 // responseText is accessible only if responseType is '' or 'text' and on older browsers49 // but we attempt to grab it anyways.50 var rawText = xhrInstance.responseText;51 var parsedBody = {};52 if (rawText) {53 // responseText is string or null54 parsedBody = attemptParseText(rawText);55 responseModel['body'] = parsedBody['body'];56 responseModel['transfer_encoding'] = parsedBody['transfer_encoding'];57 } else if (xhrInstance.response) {58 // if there is no responseText, but response exists, we'll try process it.59 logger.log('no responseText trying with xhr.response');60 if (_.isString(xhrInstance.response)) {61 logger.log('response is string. attempt to parse');62 parsedBody = attemptParseText(xhrInstance.response);63 responseModel['body'] = parsedBody['body'];64 responseModel['transfer_encoding'] = parsedBody['transfer_encoding'];65 } else if (_.isArrayBuffer(xhrInstance.response)) {66 logger.log('response is arraybuffer. attempt to parse');67 parsedBody = attemptParseBuffer(xhrInstance.response);68 responseModel['body'] = parsedBody['body'];69 responseModel['transfer_encoding'] = parsedBody['transfer_encoding'];70 } else if (_.isArray(xhrInstance.response) || _.isObject(xhrInstance.response)) {71 responseModel['body'] = xhrInstance.response;72 }73 }74 var event = {75 'request': requestModel,76 'response': responseModel77 };78 recorder(event);79 }80 }81}82function isJsonHeader(headers) {83 if (headers) {84 if(headers['content-type'] && headers['content-type'].indexOf('json') >= 0) {85 return true;86 }87 if(headers['Content-Type'] && headers['Content-Type'].indexOf('json') >= 0) {88 return true;89 }90 }91 return false;92}93function isStartJson(body) {94 if(body && typeof body === 'string') {95 var trimmedBody = _.trim(body);96 if (trimmedBody.indexOf('[') === 0 || trimmedBody.indexOf('{') === 0 ) {97 return true;98 }99 }100 return false;101}102function parseResponseHeaders(headerStr) {103 var headers = {};104 if (!headerStr) {105 return headers;106 }107 var headerPairs = headerStr.split('\u000d\u000a');108 for (var i = 0; i < headerPairs.length; i++) {109 var headerPair = headerPairs[i];110 var index = headerPair.indexOf('\u003a\u0020');111 if (index > 0) {112 var key = headerPair.substring(0, index);113 headers[key] = headerPair.substring(index + 2);114 }115 }116 return headers;117}118function convertToFullUrl(url) {119 if (url && typeof url === 'string') {120 var trimedUrl = _.trim(url);121 if (trimedUrl.indexOf('http') !== 0) {122 return HTTP_PROTOCOL + window.location.host + '/' + trimedUrl.replace(/^\./, '').replace(/^\//, '');123 } else {124 return url;125 }126 }127 return url;128}129/**130 * @param recorder131 * @returns {undoPatch}132 *133 * The recorder is a function that takes an Event and records it.134 *135 */136function captureXMLHttpRequest(recorder, options) {137 var XHR = XMLHttpRequest.prototype;138 var shouldPatchOnReadyState = options && options.eagerBodyLogging;139 var open = XHR.open;140 var send = XHR.send;141 var setRequestHeader = XHR.setRequestHeader;142 // Collect data:143 XHR.open = function(method, url) {144 logger.log('XHR open triggered');145 this._method = method;146 this._url = url;147 this._requestHeaders = {};148 this._startTime = (new Date()).toISOString();149 return open.apply(this, arguments);150 };151 XHR.setRequestHeader = function(header, value) {152 this._requestHeaders[header] = value;153 return setRequestHeader.apply(this, arguments);154 };155 XHR.send = function(postData) {156 logger.log('XHR send started for ' + this._url);157 var _self = this;158 // in case of eagerBodyLogging, we'll159 // patch onreadystatechange which is more of160 // replacement or if addEventListener does not exist.161 if (shouldPatchOnReadyState || !this.addEventListener) {162 var _onreadystatechange = this.onreadystatechange;163 this.onreadystatechange = function() {164 var readyState = _self.readyState;165 logger.log('readyState ' + readyState);166 if (readyState === XMLHttpRequest.DONE) {167 logger.log('XHR onreadystatechange DONE triggered for ' + _self._url);168 handleRequestFinished(_self, postData, recorder);169 }170 if (_onreadystatechange && _.isFunction(_onreadystatechange)) {171 logger.log('trigger old onreadystatechange');172 return _onreadystatechange.apply(this, arguments);173 }174 };175 } else {176 // this only adds another listener.177 this.addEventListener('loadend', function() {178 logger.log('XHR loadend triggered for ' + _self._url);179 handleRequestFinished(_self, postData, recorder);180 });181 }182 return send.apply(this, arguments);183 };184 var undoPatch = function () {185 XHR.open = open;186 XHR.send = send;187 XHR.setRequestHeader = setRequestHeader;188 };189 // so caller have a handle to undo the patch if needed.190 return undoPatch;191}...
networkDispatchers.js
Source:networkDispatchers.js
...88 return {89 value: (await this._object.serverAddr()) || undefined90 };91 }92 async rawResponseHeaders(params) {93 return {94 headers: await this._object.rawResponseHeaders()95 };96 }97 async sizes(params) {98 return {99 sizes: await this._object.sizes()100 };101 }102}103exports.ResponseDispatcher = ResponseDispatcher;104class RouteDispatcher extends _dispatcher.Dispatcher {105 static from(scope, route) {106 const result = (0, _dispatcher.existingDispatcher)(route);107 return result || new RouteDispatcher(scope, route);108 }...
HTTPProtocol.js
Source:HTTPProtocol.js
1dojo.provide("plugins.protocols.HTTPProtocol");2dojo.require("plugins.protocols.Protocol");3plugins.protocols.HTTPProtocol.label = 'HTTP Protocol';4dojo.declare("plugins.protocols.HTTPProtocolPane",5 [ plugins.protocols.ProtocolPane ],6 {7 templatePath: dojo.moduleUrl("plugins", "protocols/HTTPProtocol/HTTPProtocolPane.html"),8 postMixInProperties: function() {9 this.inherited('postMixInProperties', arguments);10 if (this.templatePath) this.templateString = "";11 },12 widgetsInTemplate: true,13 postCreate: function(){14 this.inherited("postCreate", arguments);15 },16 populateWithDefaults: function() {17 this.inherited('populateWithDefaults', arguments);18 this.form.attr('value', {MaxRequestContentLength: 1048576, MaxResponseContentLength: 1048576});19 },20 getHeight: function() {21 return this.pane_end.offsetTop;22 },23 _addCustomConfigValues: function(config, item) {24 var store = pion.protocols.config_store;25 config.options = [];26 // By default, RawRequestHeaders and RawResponseHeaders are both false.27 if (store.hasAttribute(item, 'RawRequestHeaders')) {28 if (store.getValue(item, 'RawRequestHeaders').toString() == 'true') {29 config.options.push('RawRequestHeaders');30 }31 }32 if (store.hasAttribute(item, 'RawResponseHeaders')) {33 if (store.getValue(item, 'RawResponseHeaders').toString() == 'true') {34 config.options.push('RawResponseHeaders');35 }36 }37 // By default, AllowUtf8Conversion is true.38 var allow_utf8_conversion = true;39 if (store.hasAttribute(item, 'AllowUtf8Conversion')) {40 allow_utf8_conversion = (store.getValue(item, 'AllowUtf8Conversion').toString() == 'true');41 }42 if (allow_utf8_conversion) {43 config.options.push('AllowUtf8Conversion');44 }45 this.updateDisabling({target: {checked: allow_utf8_conversion}});46 // By default, AllowSearchingContentForCharset is the same as AllowUtf8Conversion.47 var allow_searching_content_for_charset = allow_utf8_conversion;48 if (store.hasAttribute(item, 'AllowSearchingContentForCharset')) {49 allow_searching_content_for_charset = (store.getValue(item, 'AllowSearchingContentForCharset').toString() == 'true');50 }51 if (allow_searching_content_for_charset) {52 config.options.push('AllowSearchingContentForCharset');53 }54 },55 _makeCustomElements: function(config) {56 // If the 'allow searching' checkbox is disabled, temporarily enable it and reread the form values,57 // so that if the box is checked, AllowSearchingContentForCharset will be included in config.options.58 var allow_searching_was_disabled = this.allow_searching.attr('disabled');59 if (allow_searching_was_disabled) {60 this.allow_searching.attr('disabled', false);61 config = this.form.attr('value');62 }63 var put_data = '<RawRequestHeaders>';64 put_data += (dojo.indexOf(config.options, 'RawRequestHeaders') != -1); // 'true' iff corresponding checkbox was checked65 put_data += '</RawRequestHeaders><RawResponseHeaders>';66 put_data += (dojo.indexOf(config.options, 'RawResponseHeaders') != -1); // 'true' iff corresponding checkbox was checked67 put_data += '</RawResponseHeaders><AllowUtf8Conversion>';68 put_data += (dojo.indexOf(config.options, 'AllowUtf8Conversion') != -1); // 'true' iff corresponding checkbox was checked69 put_data += '</AllowUtf8Conversion><AllowSearchingContentForCharset>';70 put_data += (dojo.indexOf(config.options, 'AllowSearchingContentForCharset') != -1); // 'true' iff corresponding checkbox was checked71 put_data += '</AllowSearchingContentForCharset>';72 // Restore original disabled status of 'allow searching' checkbox.73 if (allow_searching_was_disabled) {74 this.allow_searching.attr('disabled', true);75 }76 return put_data;77 },78 updateDisabling: function(e) {79 if (e.target.checked) {80 dojo.removeClass(this.allow_searching_label, 'disabled');81 this.allow_searching.set('disabled', false);82 } else {83 dojo.addClass(this.allow_searching_label, 'disabled');84 this.allow_searching.set('disabled', true);85 }86 }87 }...
index.js
Source:index.js
1const Headers = require('fetch-headers')2const getStatus = require('statuses')3const bodyToIterator = require('fetch-request-body-to-async-iterator')4const { TransformStream } = require('web-streams-polyfill/ponyfill/es6')5module.exports = function makeFetch (handler) {6 return async function fetch (resource, init = {}) {7 if (!resource) throw new Error('Must specify resource')8 if (typeof resource === 'string') {9 return fetch({10 ...(init || {}),11 url: resource12 })13 }14 const {15 session,16 url,17 headers: rawHeaders,18 method: rawMethod,19 body: rawBody,20 referrer,21 signal22 } = resource23 const headers = rawHeaders ? headersToObject(rawHeaders) : {}24 const method = (rawMethod || 'GET').toUpperCase()25 const body = rawBody ? bodyToIterator(rawBody, session) : null26 const {27 statusCode,28 statusText: rawStatusText,29 headers: rawResponseHeaders,30 data31 } = await handler({32 url,33 headers,34 method,35 body,36 referrer,37 signal38 })39 const responseHeaders = new Headers(rawResponseHeaders || {})40 const statusText = rawStatusText || getStatus(statusCode)41 return new FakeResponse(statusCode, statusText, responseHeaders, data, url)42 }43}44class FakeResponse {45 constructor (status, statusText, headers, iterator, url) {46 this.body = makeBody(iterator)47 this.headers = headers48 this.url = url49 this.status = status50 this.statusText = statusText51 }52 get ok () {53 return this.status && this.status < 40054 }55 get useFinalURL () {56 return true57 }58 async arrayBuffer () {59 const buffer = await collectBuffers(this.body)60 return buffer.buffer61 }62 async text () {63 const buffer = await collectBuffers(this.body)64 return buffer.toString('utf-8')65 }66 async json () {67 return JSON.parse(await this.text())68 }69}70function makeBody (iterator) {71 const { readable, writable } = new TransformStream();72 (async () => {73 try {74 const writer = writable.getWriter()75 try {76 for await (const x of iterator) await writer.write(x)77 } finally {78 await writer.close()79 }80 } catch {81 // There was some sort of unhandled error?82 }83 })()84 return readable85}86function headersToObject (headers) {87 if (!headers) return {}88 if (typeof headers.entries === 'function') {89 const result = {}90 for (const [key, value] of headers) {91 result[key] = value92 }93 return result94 } else return headersToObject(new Headers(headers || {}))95}96async function collectBuffers (iterable) {97 const all = []98 for await (const buff of iterable) {99 all.push(Buffer.from(buff))100 }101 return Buffer.concat(all)...
XMLHttpRequest.js
Source:XMLHttpRequest.js
1'use strict';2var needle = require('needle');3var URL = require('url');4module.exports = function(window) {5 var XMLHttpRequest = function() {6 this.opts = {7 parse: false8 };9 }10 XMLHttpRequest.prototype = {11 status: 200,12 statusText: '',13 readyState: 0,14 withCredentials: false,15 getAllResponseHeaders: function() {16 return this.rawResponseHeaders;17 },18 getResponseHeader: function(header) {19 return this.responseHeaders[header.toLowerCase()];20 },21 setRequestHeader: function(header, value) {22 if (this.opts.headers === undefined)23 this.opts.headers = {};24 this.opts.headers[header] = value;25 },26 open: function(method, url, is_async, user, pass) {27 this.method = method;28 this.setRequestHeader('Referer', window.location.href);29 this.setRequestHeader('Cookie', window.document.cookie);30 this.url = URL.format(URL.resolve(window.location.href, url));31 this.async = is_async;32 this.user = user;33 this.pass = pass;34 this.readyState = 1;35 },36 overrideMimeType: function(mime) {37 },38 send: function(data) {39 var self = this;40 window.__stackPush();41 console.log('[libxmljs-dom] XMLHttpRequest: '+this.method+' '+this.url);42 needle.request(this.method, this.url, data, this.opts, function(err, res, data) {43 if (err) console.log('[libxmljs-dom] XMLHttpRequest: '+err);44 self.readyState = 4;45 self.response = data.toString();46 self.responseText = data.toString();47 self.responseType = "text";48 self.responseHeaders = res.headers;49 var rawHeaders = res.socket._httpMessage._header;50 self.rawResponseHeaders = rawHeaders.substr(rawHeaders.indexOf("\r\n")+2);51 self.status = res.statusCode;52 self.statusText = res.statusMessage;53 if (self.onreadystatechange !== undefined) {54 self.onreadystatechange();55 }else if (self.onload !== undefined) {56 self.onload();57 }58 window.__stackPop();59 })60 }61 }62 return XMLHttpRequest;...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const rawResponseHeaders = await page._client.send('Network.getResponseBody', { requestId: 'request-id' });7 console.log(rawResponseHeaders);8 await browser.close();9})();10{11}12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 const rawRequestHeaders = await page._client.send('Network.getResponseBody', { requestId: 'request-id' });18 console.log(rawRequestHeaders);19 await browser.close();20})();21{22}
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 console.log(await response.rawResponseHeaders());7 await browser.close();8})();9Content-Type: text/html; charset=UTF-810Set-Cookie: __cfduid=d8c6f0a6a7e6e0b6e2d6d9f6c3e3a3a841594954133; expires=Fri, 24-Jul-20 14:53:13 GMT; path=/; domain=.example.com; HttpOnly; SameSite=Lax11Set-Cookie: __cf_bm=2e8a8b9e9b5a0b5c5b1d8f0a5d5b1a5f3f5d5b5a-1594954133-1800-AXV8WY4b4vVx2zNt1lZ8Wz9XlFV0hKpD5uY8YwYtD0bFkZIjHsJ8Ks9XfZB2Q2T1C1bYwYnYdYrR; path=/; domain=.example.com; HttpOnly; Secure; SameSite=None12Set-Cookie: __cf_bm=2e8a8b9e9b5a0b5c5b1d8f0a5d5b1a5f3f5d5b5a-1594954133-1800-AXV8WY4b4vVx2zNt1lZ8Wz9XlFV0hKpD5uY8YwYtD0bFkZIjHsJ8Ks9XfZB2Q2T1C1bYwYnYdYrR; path=/; domain=.example
Using AI Code Generation
1const { chromium, webkit, firefox } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 const headers = await response.rawResponseHeaders();7 console.log(headers);8 await browser.close();9})();10const { chromium, webkit, firefox } = require('playwright');11(async () => {12 const browser = await chromium.launch({ headless: false });13 const context = await browser.newContext();14 const page = await context.newPage();15 const headers = await response.rawRequestHeaders();16 console.log(headers);17 await browser.close();18})();19const { chromium, webkit, firefox } = require('playwright');20(async () => {21 const browser = await chromium.launch({ headless: false });22 const context = await browser.newContext();23 const page = await context.newPage();24 const headers = await response.rawRequest();25 console.log(headers);26 await browser.close();27})();28const { chromium, webkit, firefox } = require('playwright');29(async () => {30 const browser = await chromium.launch({ headless: false });31 const context = await browser.newContext();32 const page = await context.newPage();33 const headers = await response.rawResponse();34 console.log(headers);35 await browser.close();36})();37const { chromium, webkit, firefox } = require('playwright');38(async () => {39 const browser = await chromium.launch({ headless: false });40 const context = await browser.newContext();41 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 const page = await context.newPage();6 await page.route('**/*', route => {7 route.fulfill({8 headers: {9 },10 });11 });12 const request = await page.waitForRequest(request => request.url().includes('playwright.dev'));13 console.log(request.rawResponseHeaders());14 await browser.close();15})();16What is the difference between request.headers() and request.rawResponseHeaders()?17Example 2: Using rawRequestHeaders() method18const { chromium } = require('playwright');19(async () => {20 const browser = await chromium.launch();21 const context = await browser.newContext();22 const page = await context.newPage();23 await page.route('**/*', route => {24 route.fulfill({25 headers: {26 },27 });28 });29 const request = await page.waitForRequest(request => request.url().includes('playwright.dev'));30 console.log(request.rawRequestHeaders());31 await browser.close();32})();
Using AI Code Generation
1const rawResponseHeaders = await page.evaluate(() => {2 return window.__playwright__internal__rawResponseHeaders;3});4console.log(rawResponseHeaders);5await browser.close();6})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 page.route('**', route => route.fulfill({7 headers: {8 },9 }));10 const response = await page.waitForResponse('**');11 const headers = response.rawResponseHeaders();12 console.log(headers['x-custom-header']);13 await browser.close();14})();
Using AI Code Generation
1const { Page } = require('playwright/lib/server/page');2Page.prototype.rawResponseHeaders = function (requestId) {3 const request = this._requestIdToRequest.get(requestId);4 if (!request) throw new Error('Request not found');5 return request._rawResponseHeaders;6};7const responseHeaders = await page.rawResponseHeaders(requestId);8console.log(responseHeaders);9const { Page } = require('playwright/lib/server/page');10Page.prototype.rawResponseHeaders = function (requestId) {11 const request = this._requestIdToRequest.get(requestId);12 if (!request) throw new Error('Request not found');13 return request._rawResponseHeaders;14};15const responseHeaders = await page.rawResponseHeaders(requestId);16console.log(responseHeaders);17const { Page } = require('playwright/lib/server/page');18Page.prototype.rawResponseHeaders = function (requestId) {19 const request = this._requestIdToRequest.get(requestId);20 if (!request) throw new Error('Request not found');21 return request._rawResponseHeaders;22};23const responseHeaders = await page.rawResponseHeaders(requestId);24console.log(responseHeaders);25const { Page } = require('playwright/lib/server/page');26Page.prototype.rawResponseHeaders = function (requestId) {27 const request = this._requestIdToRequest.get(requestId);28 if (!request) throw new Error('Request not found');29 return request._rawResponseHeaders;30};31const responseHeaders = await page.rawResponseHeaders(requestId);32console.log(responseHeaders);
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!!