How to use xhr method in wpt

Best JavaScript code snippet using wpt

angular-file-upload-shim.js

Source:angular-file-upload-shim.js Github

copy

Full Screen

1/**!2 * AngularJS file upload shim for HTML5 FormData3 * @author Danial <danial.farid@gmail.com>4 * @version 1.3.15 */6(function() {7var hasFlash = function() {8 try {9 var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');10 if (fo) return true;11 } catch(e) {12 if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined) return true;13 }14 return false;15}16 17if (window.XMLHttpRequest) {18 if (window.FormData) {19 // allow access to Angular XHR private field: https://github.com/angular/angular.js/issues/193420 window.XMLHttpRequest = (function(origXHR) {21 return function() {22 var xhr = new origXHR();23 xhr.setRequestHeader = (function(orig) {24 return function(header, value) {25 if (header === '__setXHR_') {26 var val = value(xhr);27 // fix for angular < 1.2.028 if (val instanceof Function) {29 val(xhr);30 }31 } else {32 orig.apply(xhr, arguments);33 }34 }35 })(xhr.setRequestHeader);36 return xhr;37 }38 })(window.XMLHttpRequest);39 } else {40 window.XMLHttpRequest = (function(origXHR) {41 return function() {42 var xhr = new origXHR();43 var origSend = xhr.send;44 xhr.__requestHeaders = [];45 xhr.open = (function(orig) {46 if (!xhr.upload) xhr.upload = {};47 xhr.__listeners = [];48 xhr.upload.addEventListener = function(t, fn, b) {49 xhr.__listeners[t] = fn;50 };51 return function(m, url, b) {52 orig.apply(xhr, [m, url, b]);53 xhr.__url = url;54 }55 })(xhr.open);56 xhr.getResponseHeader = (function(orig) {57 return function(h) {58 return xhr.__fileApiXHR ? xhr.__fileApiXHR.getResponseHeader(h) : orig.apply(xhr, [h]);59 }60 })(xhr.getResponseHeader);61 xhr.getAllResponseHeaders = (function(orig) {62 return function() {63 return xhr.__fileApiXHR ? xhr.__fileApiXHR.getAllResponseHeaders() : orig.apply(xhr);64 }65 })(xhr.getAllResponseHeaders);66 xhr.abort = (function(orig) {67 return function() {68 return xhr.__fileApiXHR ? xhr.__fileApiXHR.abort() : (orig == null ? null : orig.apply(xhr));69 }70 })(xhr.abort);71 xhr.setRequestHeader = (function(orig) {72 return function(header, value) {73 if (header === '__setXHR_') {74 var val = value(xhr);75 // fix for angular < 1.2.076 if (val instanceof Function) {77 val(xhr);78 }79 } else {80 orig.apply(xhr, arguments);81 }82 }83 })(xhr.setRequestHeader);84 xhr.send = function() {85 if (arguments[0] && arguments[0].__isShim) {86 var formData = arguments[0];87 var config = {88 url: xhr.__url,89 complete: function(err, fileApiXHR) {90 if (!err && xhr.__listeners['load']) 91 xhr.__listeners['load']({type: 'load', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true});92 if (!err && xhr.__listeners['loadend']) 93 xhr.__listeners['loadend']({type: 'loadend', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true});94 if (err === 'abort' && xhr.__listeners['abort']) 95 xhr.__listeners['abort']({type: 'abort', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true});96 if (fileApiXHR.status !== undefined) Object.defineProperty(xhr, 'status', {get: function() {return fileApiXHR.status}});97 if (fileApiXHR.statusText !== undefined) Object.defineProperty(xhr, 'statusText', {get: function() {return fileApiXHR.statusText}});98 Object.defineProperty(xhr, 'readyState', {get: function() {return 4}});99 if (fileApiXHR.response !== undefined) Object.defineProperty(xhr, 'response', {get: function() {return fileApiXHR.response}});100 Object.defineProperty(xhr, 'responseText', {get: function() {return fileApiXHR.responseText}});101 xhr.__fileApiXHR = fileApiXHR;102 xhr.onreadystatechange();103 },104 progress: function(e) {105 e.target = xhr;106 xhr.__listeners['progress'] && xhr.__listeners['progress'](e);107 xhr.__total = e.total;108 xhr.__loaded = e.loaded;109 },110 headers: xhr.__requestHeaders111 }112 config.data = {};113 config.files = {}114 for (var i = 0; i < formData.data.length; i++) {115 var item = formData.data[i];116 if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) {117 config.files[item.key] = item.val;118 } else {119 config.data[item.key] = item.val;120 }121 }122 setTimeout(function() {123 if (!hasFlash()) {124 throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';125 }126 xhr.__fileApiXHR = FileAPI.upload(config);127 }, 1);128 } else {129 origSend.apply(xhr, arguments);130 }131 }132 return xhr;133 }134 })(window.XMLHttpRequest);135 window.XMLHttpRequest.__hasFlash = hasFlash();136 }137 window.XMLHttpRequest.__isShim = true;138}139if (!window.FormData) {140 var wrapFileApi = function(elem) {141 if (!hasFlash()) {142 throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';143 }144 if (!elem.__isWrapped && (elem.getAttribute('ng-file-select') != null || elem.getAttribute('data-ng-file-select') != null)) {145 var wrap = document.createElement('div');146 wrap.innerHTML = '<div class="js-fileapi-wrapper" style="position:relative; overflow:hidden"></div>';147 wrap = wrap.firstChild;148 var parent = elem.parentNode;149 parent.insertBefore(wrap, elem);150 parent.removeChild(elem);151 wrap.appendChild(elem);152 elem.__isWrapped = true;153 }154 };155 var changeFnWrapper = function(fn) {156 return function(evt) {157 var files = FileAPI.getFiles(evt);158 if (!evt.target) {159 evt.target = {};160 }161 evt.target.files = files;162 evt.target.files.item = function(i) {163 return evt.target.files[i] || null;164 }165 fn(evt);166 };167 };168 var isFileChange = function(elem, e) {169 return (e.toLowerCase() === 'change' || e.toLowerCase() === 'onchange') && elem.getAttribute('type') == 'file';170 }171 if (HTMLInputElement.prototype.addEventListener) {172 HTMLInputElement.prototype.addEventListener = (function(origAddEventListener) {173 return function(e, fn, b, d) {174 if (isFileChange(this, e)) {175 wrapFileApi(this);176 origAddEventListener.apply(this, [e, changeFnWrapper(fn), b, d]);177 } else {178 origAddEventListener.apply(this, [e, fn, b, d]);179 }180 }181 })(HTMLInputElement.prototype.addEventListener);182 }183 if (HTMLInputElement.prototype.attachEvent) {184 HTMLInputElement.prototype.attachEvent = (function(origAttachEvent) {185 return function(e, fn) {186 if (isFileChange(this, e)) {187 wrapFileApi(this);188 origAttachEvent.apply(this, [e, changeFnWrapper(fn)]);189 } else {190 origAttachEvent.apply(this, [e, fn]);191 }192 }193 })(HTMLInputElement.prototype.attachEvent);194 }195 window.FormData = FormData = function() {196 return {197 append: function(key, val, name) {198 this.data.push({199 key: key,200 val: val,201 name: name202 });203 },204 data: [],205 __isShim: true206 };207 };208 (function () {209 //load FileAPI210 if (!window.FileAPI) {211 window.FileAPI = {};212 }213 if (!FileAPI.upload) {214 var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src;215 if (window.FileAPI.jsUrl) {216 jsUrl = window.FileAPI.jsUrl;217 } else if (window.FileAPI.jsPath) {218 basePath = window.FileAPI.jsPath;219 } else {220 for (i = 0; i < allScripts.length; i++) {221 src = allScripts[i].src;222 index = src.indexOf('angular-file-upload-shim.js')223 if (index == -1) {224 index = src.indexOf('angular-file-upload-shim.min.js');225 }226 if (index > -1) {227 basePath = src.substring(0, index);228 break;229 }230 }231 }232 if (FileAPI.staticPath == null) FileAPI.staticPath = basePath;233 script.setAttribute('src', jsUrl || basePath + "FileAPI.min.js");234 document.getElementsByTagName('head')[0].appendChild(script);235 FileAPI.hasFlash = hasFlash();236 }237 })();238}239if (!window.FileReader) {240 window.FileReader = function() {241 var _this = this, loadStarted = false;242 this.listeners = {};243 this.addEventListener = function(type, fn) {244 _this.listeners[type] = _this.listeners[type] || [];245 _this.listeners[type].push(fn);246 };247 this.removeEventListener = function(type, fn) {248 _this.listeners[type] && _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1);249 };250 this.dispatchEvent = function(evt) {251 var list = _this.listeners[evt.type];252 if (list) {253 for (var i = 0; i < list.length; i++) {254 list[i].call(_this, evt);255 }256 }257 };258 this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null;259 function constructEvent(type, evt) {260 var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error};261 if (evt.result != null) e.target.result = evt.result;262 return e;263 };264 var listener = function(evt) {265 if (!loadStarted) {266 loadStarted = true;267 _this.onloadstart && this.onloadstart(constructEvent('loadstart', evt));268 }269 if (evt.type === 'load') {270 _this.onloadend && _this.onloadend(constructEvent('loadend', evt));271 var e = constructEvent('load', evt);272 _this.onload && _this.onload(e);273 _this.dispatchEvent(e);274 } else if (evt.type === 'progress') {275 var e = constructEvent('progress', evt);276 _this.onprogress && _this.onprogress(e);277 _this.dispatchEvent(e);278 } else {279 var e = constructEvent('error', evt);280 _this.onerror && _this.onerror(e);281 _this.dispatchEvent(e);282 }283 };284 this.readAsArrayBuffer = function(file) {285 FileAPI.readAsBinaryString(file, listener);286 }287 this.readAsBinaryString = function(file) {288 FileAPI.readAsBinaryString(file, listener);289 }290 this.readAsDataURL = function(file) {291 FileAPI.readAsDataURL(file, listener);292 }293 this.readAsText = function(file) {294 FileAPI.readAsText(file, listener);295 }296 }297}...

Full Screen

Full Screen

network.js

Source:network.js Github

copy

Full Screen

1/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */2/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */3/* Copyright 2012 Mozilla Foundation4 *5 * Licensed under the Apache License, Version 2.0 (the "License");6 * you may not use this file except in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17// NOTE: Be careful what goes in this file, as it is also used from the context18// of the addon. So using warn/error in here will break the addon.19'use strict';20//#if (FIREFOX || MOZCENTRAL)21//22//Components.utils.import('resource://gre/modules/Services.jsm');23//24//var EXPORTED_SYMBOLS = ['NetworkManager'];25//26//var console = {27// log: function console_log(aMsg) {28// var msg = 'network.js: ' + (aMsg.join ? aMsg.join('') : aMsg);29// Services.console.logStringMessage(msg);30// // TODO(mack): dump() doesn't seem to work here...31// dump(msg + '\n');32// }33//}34//#endif35var NetworkManager = (function NetworkManagerClosure() {36 var OK_RESPONSE = 200;37 var PARTIAL_CONTENT_RESPONSE = 206;38 function NetworkManager(url, args) {39 this.url = url;40 args = args || {};41 this.isHttp = /^https?:/i.test(url);42 this.httpHeaders = (this.isHttp && args.httpHeaders) || {};43 this.withCredentials = args.withCredentials || false;44 this.getXhr = args.getXhr ||45 function NetworkManager_getXhr() {46//#if B2G47// return new XMLHttpRequest({ mozSystem: true });48//#else49 return new XMLHttpRequest();50//#endif51 };52 this.currXhrId = 0;53 this.pendingRequests = {};54 this.loadedRequests = {};55 }56 function getArrayBuffer(xhr) {57 var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse ||58 xhr.responseArrayBuffer || xhr.response);59 if (typeof data !== 'string') {60 return data;61 }62 var length = data.length;63 var buffer = new Uint8Array(length);64 for (var i = 0; i < length; i++) {65 buffer[i] = data.charCodeAt(i) & 0xFF;66 }67 return buffer;68 }69 NetworkManager.prototype = {70 requestRange: function NetworkManager_requestRange(begin, end, listeners) {71 var args = {72 begin: begin,73 end: end74 };75 for (var prop in listeners) {76 args[prop] = listeners[prop];77 }78 return this.request(args);79 },80 requestFull: function NetworkManager_requestRange(listeners) {81 return this.request(listeners);82 },83 request: function NetworkManager_requestRange(args) {84 var xhr = this.getXhr();85 var xhrId = this.currXhrId++;86 var pendingRequest = this.pendingRequests[xhrId] = {87 xhr: xhr88 };89 xhr.open('GET', this.url);90 xhr.withCredentials = this.withCredentials;91 for (var property in this.httpHeaders) {92 var value = this.httpHeaders[property];93 if (typeof value === 'undefined') {94 continue;95 }96 xhr.setRequestHeader(property, value);97 }98 if (this.isHttp && 'begin' in args && 'end' in args) {99 var rangeStr = args.begin + '-' + (args.end - 1);100 xhr.setRequestHeader('Range', 'bytes=' + rangeStr);101 pendingRequest.expectedStatus = 206;102 } else {103 pendingRequest.expectedStatus = 200;104 }105 xhr.mozResponseType = xhr.responseType = 'arraybuffer';106 if (args.onProgress) {107 xhr.onprogress = args.onProgress;108 }109 if (args.onError) {110 xhr.onerror = function(evt) {111 args.onError(xhr.status);112 };113 }114 xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);115 pendingRequest.onHeadersReceived = args.onHeadersReceived;116 pendingRequest.onDone = args.onDone;117 pendingRequest.onError = args.onError;118 xhr.send(null);119 return xhrId;120 },121 onStateChange: function NetworkManager_onStateChange(xhrId, evt) {122 var pendingRequest = this.pendingRequests[xhrId];123 if (!pendingRequest) {124 // Maybe abortRequest was called...125 return;126 }127 var xhr = pendingRequest.xhr;128 if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {129 pendingRequest.onHeadersReceived();130 delete pendingRequest.onHeadersReceived;131 }132 if (xhr.readyState !== 4) {133 return;134 }135 if (!(xhrId in this.pendingRequests)) {136 // The XHR request might have been aborted in onHeadersReceived()137 // callback, in which case we should abort request138 return;139 }140 delete this.pendingRequests[xhrId];141 // success status == 0 can be on ftp, file and other protocols142 if (xhr.status === 0 && this.isHttp) {143 if (pendingRequest.onError) {144 pendingRequest.onError(xhr.status);145 }146 return;147 }148 var xhrStatus = xhr.status || OK_RESPONSE;149 // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:150 // "A server MAY ignore the Range header". This means it's possible to151 // get a 200 rather than a 206 response from a range request.152 var ok_response_on_range_request =153 xhrStatus === OK_RESPONSE &&154 pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;155 if (!ok_response_on_range_request &&156 xhrStatus !== pendingRequest.expectedStatus) {157 if (pendingRequest.onError) {158 pendingRequest.onError(xhr.status);159 }160 return;161 }162 this.loadedRequests[xhrId] = true;163 var chunk = getArrayBuffer(xhr);164 if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {165 var rangeHeader = xhr.getResponseHeader('Content-Range');166 var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);167 var begin = parseInt(matches[1], 10);168 pendingRequest.onDone({169 begin: begin,170 chunk: chunk171 });172 } else {173 pendingRequest.onDone({174 begin: 0,175 chunk: chunk176 });177 }178 },179 hasPendingRequests: function NetworkManager_hasPendingRequests() {180 for (var xhrId in this.pendingRequests) {181 return true;182 }183 return false;184 },185 getRequestXhr: function NetworkManager_getXhr(xhrId) {186 return this.pendingRequests[xhrId].xhr;187 },188 isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {189 return xhrId in this.pendingRequests;190 },191 isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {192 return xhrId in this.loadedRequests;193 },194 abortAllRequests: function NetworkManager_abortAllRequests() {195 for (var xhrId in this.pendingRequests) {196 this.abortRequest(xhrId | 0);197 }198 },199 abortRequest: function NetworkManager_abortRequest(xhrId) {200 var xhr = this.pendingRequests[xhrId].xhr;201 delete this.pendingRequests[xhrId];202 xhr.abort();203 }204 };205 return NetworkManager;...

Full Screen

Full Screen

from_streaming_xhr.test.ts

Source:from_streaming_xhr.test.ts Github

copy

Full Screen

1/*2 * Licensed to Elasticsearch B.V. under one or more contributor3 * license agreements. See the NOTICE file distributed with4 * this work for additional information regarding copyright5 * ownership. Elasticsearch B.V. licenses this file to you under6 * the Apache License, Version 2.0 (the "License"); you may7 * not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing,13 * software distributed under the License is distributed on an14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15 * KIND, either express or implied. See the License for the16 * specific language governing permissions and limitations17 * under the License.18 */19import { fromStreamingXhr } from './from_streaming_xhr';20const createXhr = (): XMLHttpRequest =>21 (({22 onprogress: () => {},23 onreadystatechange: () => {},24 readyState: 0,25 responseText: '',26 status: 0,27 } as unknown) as XMLHttpRequest);28test('returns observable', () => {29 const xhr = createXhr();30 const observable = fromStreamingXhr(xhr);31 expect(typeof observable.subscribe).toBe('function');32});33test('emits an event to observable', () => {34 const xhr = createXhr();35 const observable = fromStreamingXhr(xhr);36 const spy = jest.fn();37 observable.subscribe(spy);38 expect(spy).toHaveBeenCalledTimes(0);39 (xhr as any).responseText = 'foo';40 xhr.onprogress!({} as any);41 expect(spy).toHaveBeenCalledTimes(1);42 expect(spy).toHaveBeenCalledWith('foo');43});44test('streams multiple events to observable', () => {45 const xhr = createXhr();46 const observable = fromStreamingXhr(xhr);47 const spy = jest.fn();48 observable.subscribe(spy);49 expect(spy).toHaveBeenCalledTimes(0);50 (xhr as any).responseText = '1';51 xhr.onprogress!({} as any);52 (xhr as any).responseText = '12';53 xhr.onprogress!({} as any);54 (xhr as any).responseText = '123';55 xhr.onprogress!({} as any);56 expect(spy).toHaveBeenCalledTimes(3);57 expect(spy.mock.calls[0][0]).toBe('1');58 expect(spy.mock.calls[1][0]).toBe('2');59 expect(spy.mock.calls[2][0]).toBe('3');60});61test('completes observable when request reaches end state', () => {62 const xhr = createXhr();63 const observable = fromStreamingXhr(xhr);64 const next = jest.fn();65 const complete = jest.fn();66 observable.subscribe({67 next,68 complete,69 });70 (xhr as any).responseText = '1';71 xhr.onprogress!({} as any);72 (xhr as any).responseText = '2';73 xhr.onprogress!({} as any);74 expect(complete).toHaveBeenCalledTimes(0);75 (xhr as any).readyState = 4;76 (xhr as any).status = 200;77 xhr.onreadystatechange!({} as any);78 expect(complete).toHaveBeenCalledTimes(1);79});80test('errors observable if request returns with error', () => {81 const xhr = createXhr();82 const observable = fromStreamingXhr(xhr);83 const next = jest.fn();84 const complete = jest.fn();85 const error = jest.fn();86 observable.subscribe({87 next,88 complete,89 error,90 });91 (xhr as any).responseText = '1';92 xhr.onprogress!({} as any);93 (xhr as any).responseText = '2';94 xhr.onprogress!({} as any);95 expect(complete).toHaveBeenCalledTimes(0);96 (xhr as any).readyState = 4;97 (xhr as any).status = 400;98 xhr.onreadystatechange!({} as any);99 expect(complete).toHaveBeenCalledTimes(0);100 expect(error).toHaveBeenCalledTimes(1);101 expect(error.mock.calls[0][0]).toBeInstanceOf(Error);102 expect(error.mock.calls[0][0].message).toMatchInlineSnapshot(103 `"Batch request failed with status 400"`104 );105});106test('when .onprogress called multiple times with same text, does not create new observable events', () => {107 const xhr = createXhr();108 const observable = fromStreamingXhr(xhr);109 const spy = jest.fn();110 observable.subscribe(spy);111 expect(spy).toHaveBeenCalledTimes(0);112 (xhr as any).responseText = '1';113 xhr.onprogress!({} as any);114 (xhr as any).responseText = '1';115 xhr.onprogress!({} as any);116 (xhr as any).responseText = '12';117 xhr.onprogress!({} as any);118 (xhr as any).responseText = '12';119 xhr.onprogress!({} as any);120 (xhr as any).responseText = '123';121 xhr.onprogress!({} as any);122 expect(spy).toHaveBeenCalledTimes(3);123 expect(spy.mock.calls[0][0]).toBe('1');124 expect(spy.mock.calls[1][0]).toBe('2');125 expect(spy.mock.calls[2][0]).toBe('3');126});127test('generates new observable events on .onreadystatechange', () => {128 const xhr = createXhr();129 const observable = fromStreamingXhr(xhr);130 const spy = jest.fn();131 observable.subscribe(spy);132 expect(spy).toHaveBeenCalledTimes(0);133 (xhr as any).responseText = '{"foo":"bar"}';134 xhr.onreadystatechange!({} as any);135 (xhr as any).responseText = '{"foo":"bar"}\n';136 xhr.onreadystatechange!({} as any);137 (xhr as any).responseText = '{"foo":"bar"}\n123';138 xhr.onreadystatechange!({} as any);139 expect(spy).toHaveBeenCalledTimes(3);140 expect(spy.mock.calls[0][0]).toBe('{"foo":"bar"}');141 expect(spy.mock.calls[1][0]).toBe('\n');142 expect(spy.mock.calls[2][0]).toBe('123');143});144test('.onreadystatechange and .onprogress can be called in any order', () => {145 const xhr = createXhr();146 const observable = fromStreamingXhr(xhr);147 const spy = jest.fn();148 observable.subscribe(spy);149 expect(spy).toHaveBeenCalledTimes(0);150 (xhr as any).responseText = '{"foo":"bar"}';151 xhr.onreadystatechange!({} as any);152 xhr.onprogress!({} as any);153 (xhr as any).responseText = '{"foo":"bar"}\n';154 xhr.onprogress!({} as any);155 xhr.onreadystatechange!({} as any);156 (xhr as any).responseText = '{"foo":"bar"}\n123';157 xhr.onreadystatechange!({} as any);158 xhr.onprogress!({} as any);159 xhr.onreadystatechange!({} as any);160 xhr.onprogress!({} as any);161 expect(spy).toHaveBeenCalledTimes(3);162 expect(spy.mock.calls[0][0]).toBe('{"foo":"bar"}');163 expect(spy.mock.calls[1][0]).toBe('\n');164 expect(spy.mock.calls[2][0]).toBe('123');...

Full Screen

Full Screen

xhr.js

Source:xhr.js Github

copy

Full Screen

1/*2 * xhr.js - XMLHttpRequest helper class3 * (c) 2008-2010 Jo-Philipp Wich4 */5XHR = function()6{7 this.reinit = function()8 {9 if (window.XMLHttpRequest) {10 this._xmlHttp = new XMLHttpRequest();11 }12 else if (window.ActiveXObject) {13 this._xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");14 }15 else {16 alert("xhr.js: XMLHttpRequest is not supported by this browser!");17 }18 }19 this.busy = function() {20 if (!this._xmlHttp)21 return false;22 switch (this._xmlHttp.readyState)23 {24 case 1:25 case 2:26 case 3:27 return true;28 default:29 return false;30 }31 }32 this.abort = function() {33 if (this.busy())34 this._xmlHttp.abort();35 }36 this.get = function(url,data,callback)37 {38 this.reinit();39 var xhr = this._xmlHttp;40 var code = this._encode(data);41 url = location.protocol + '//' + location.host + url;42 if (code)43 if (url.substr(url.length-1,1) == '&')44 url += code;45 else46 url += '?' + code;47 xhr.open('GET', url, true);48 xhr.onreadystatechange = function()49 {50 if (xhr.readyState == 4) {51 var json = null;52 if (xhr.getResponseHeader("Content-Type") == "application/json") {53 try {54 json = eval('(' + xhr.responseText + ')');55 }56 catch(e) {57 json = null;58 }59 }60 callback(xhr, json);61 }62 }63 xhr.send(null);64 }65 this.post = function(url,data,callback)66 {67 this.reinit();68 var xhr = this._xmlHttp;69 var code = this._encode(data);70 xhr.onreadystatechange = function()71 {72 if (xhr.readyState == 4)73 callback(xhr);74 }75 xhr.open('POST', url, true);76 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');77 xhr.setRequestHeader('Content-length', code.length);78 xhr.setRequestHeader('Connection', 'close');79 xhr.send(code);80 }81 this.cancel = function()82 {83 this._xmlHttp.onreadystatechange = function(){};84 this._xmlHttp.abort();85 }86 this.send_form = function(form,callback,extra_values)87 {88 var code = '';89 for (var i = 0; i < form.elements.length; i++)90 {91 var e = form.elements[i];92 if (e.options)93 {94 code += (code ? '&' : '') +95 form.elements[i].name + '=' + encodeURIComponent(96 e.options[e.selectedIndex].value97 );98 }99 else if (e.length)100 {101 for (var j = 0; j < e.length; j++)102 if (e[j].name) {103 code += (code ? '&' : '') +104 e[j].name + '=' + encodeURIComponent(e[j].value);105 }106 }107 else108 {109 code += (code ? '&' : '') +110 e.name + '=' + encodeURIComponent(e.value);111 }112 }113 if (typeof extra_values == 'object')114 for (var key in extra_values)115 code += (code ? '&' : '') +116 key + '=' + encodeURIComponent(extra_values[key]);117 return(118 (form.method == 'get')119 ? this.get(form.getAttribute('action'), code, callback)120 : this.post(form.getAttribute('action'), code, callback)121 );122 }123 this._encode = function(obj)124 {125 obj = obj ? obj : { };126 obj['_'] = Math.random();127 if (typeof obj == 'object')128 {129 var code = '';130 var self = this;131 for (var k in obj)132 code += (code ? '&' : '') +133 k + '=' + encodeURIComponent(obj[k]);134 return code;135 }136 return obj;137 }138}139XHR.get = function(url, data, callback)140{141 (new XHR()).get(url, data, callback);142}143XHR.poll = function(interval, url, data, callback)144{145 if (isNaN(interval) || interval < 1)146 interval = 5;147 if (!XHR._q)148 {149 XHR._t = 0;150 XHR._q = [ ];151 XHR._r = function() {152 for (var i = 0, e = XHR._q[0]; i < XHR._q.length; e = XHR._q[++i])153 {154 if (!(XHR._t % e.interval) && !e.xhr.busy())155 e.xhr.get(e.url, e.data, e.callback);156 }157 XHR._t++;158 };159 }160 XHR._q.push({161 interval: interval,162 callback: callback,163 url: url,164 data: data,165 xhr: new XHR()166 });167 XHR.run();168}169XHR.halt = function()170{171 if (XHR._i)172 {173 /* show & set poll indicator */174 try {175 document.getElementById('xhr_poll_status').style.display = '';176 document.getElementById('xhr_poll_status_on').style.display = 'none';177 document.getElementById('xhr_poll_status_off').style.display = '';178 } catch(e) { }179 window.clearInterval(XHR._i);180 XHR._i = null;181 }182}183XHR.run = function()184{185 if (XHR._r && !XHR._i)186 {187 /* show & set poll indicator */188 try {189 document.getElementById('xhr_poll_status').style.display = '';190 document.getElementById('xhr_poll_status_on').style.display = '';191 document.getElementById('xhr_poll_status_off').style.display = 'none';192 } catch(e) { }193 /* kick first round manually to prevent one second lag when setting up194 * the poll interval */195 XHR._r();196 XHR._i = window.setInterval(XHR._r, 1000);197 }198}199XHR.running = function()200{201 return !!(XHR._r && XHR._i);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test status: ' + data.statusText);5 console.log('Test ID: ' + data.data.testId);6});7var wpt = require('webpagetest');8var wpt = new WebPageTest('www.webpagetest.org');9 if (err) return console.error(err);10 console.log('Test status: ' + data.statusText);11 console.log('Test ID: ' + data.data.testId);12});13var wpt = require('webpagetest');14var wpt = new WebPageTest('www.webpagetest.org');15 if (err) return console.error(err);16 console.log('Test status: ' + data.statusText);17 console.log('Test ID: ' + data.data.testId);18});19var wpt = require('webpagetest');20var wpt = new WebPageTest('www.webpagetest.org');21 if (err) return console.error(err);22 console.log('Test status: ' + data.statusText);23 console.log('Test ID: ' + data.data.testId);24});25var wpt = require('webpagetest');26var wpt = new WebPageTest('www.webpagetest.org');

Full Screen

Using AI Code Generation

copy

Full Screen

1var xhr = new XMLHttpRequest();2xhr.onreadystatechange = function() {3 if (xhr.readyState == 4) {4 var resp = JSON.parse(xhr.responseText);5 console.log(resp);6 }7}8xhr.send();9var script = document.createElement('script');10document.getElementsByTagName('head')[0].appendChild(script);11function callback(resp) {12 console.log(resp);13}14var script = document.createElement('script');15document.getElementsByTagName('head')[0].appendChild(script);16var script = document.createElement('script');17document.getElementsByTagName('head')[0].appendChild(script);18var script = document.createElement('script');19document.getElementsByTagName('head')[0].appendChild(script);20var script = document.createElement('script');21document.getElementsByTagName('head')[0].appendChild(script);22var script = document.createElement('script');23document.getElementsByTagName('head')[0].appendChild(script);

Full Screen

Using AI Code Generation

copy

Full Screen

1var xhr = new XMLHttpRequest();2xhr.send();3console.log(xhr.responseText);4.then(response => response.text())5.then(data => console.log(data));6async function fetchAsync () {7 let data = await response.text();8 console.log(data);9}10fetchAsync()11(async () => {12 let data = await response.text();13 console.log(data);14})();15(async () => {16 try {17 let data = await response.text();18 console.log(data);19 } catch (error) {20 console.log(error);21 }22})();23(async () => {24 try {25 let data = await response.text();26 console.log(data);27 } catch (error) {28 console.log(error);29 } finally {30 console.log("done");31 }32})();33(async () => {34 try {35 let data = await response.text();36 console.log(data);37 } catch (error) {38 console.log(error);39 } finally {40 console.log("done");41 }42})();43(async () => {44 try {45 let data = await response.text();46 console.log(data);47 } catch (error) {48 console.log(error);49 } finally {50 console.log("done");51 }52})();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var fs = require('fs');3var options = {4};5var wpt = new WebPageTest('www.webpagetest.org', 'A.0a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p');6wpt.runTest(testUrl, {7}, function (err, data) {8 if (err) return console.error(err);9 console.log('Test Results for: ' + data.data.summary);10 console.log('First View (fv) Speed Index: ' + data.data.median.firstView.SpeedIndex);11 console.log('Repeat View (rv) Speed Index: ' + data.data.median.repeatView.SpeedIndex);12 console.log('First View (fv) Load Time: ' + data.data.median.firstView.loadTime);13 console.log('Repeat View (rv) Load Time: ' + data.data.median.repeatView.loadTime);14 console.log('First View (fv) TTFB: ' + data.data.median.firstView.TTFB);15 console.log('Repeat View (rv) TTFB: ' + data.data.median.repeatView.TTFB);16 console.log('First View (fv) Start Render: ' + data.data.median.firstView.render);17 console.log('Repeat View (rv) Start Render: ' + data.data.median.repeatView.render);18 console.log('First View (fv) Visual Complete: ' + data.data.median.firstView.visualComplete);19 console.log('Repeat View (rv) Visual Complete: ' + data.data.median.repeatView.visualComplete);20 console.log('First View (fv) Speed Index: ' + data.data.median.firstView.SpeedIndex);21 console.log('Repeat View (rv) Speed Index: ' + data.data.median.repeatView.SpeedIndex);22 console.log('First View (fv) Speed Index: ' + data.data.median.firstView.SpeedIndex);

Full Screen

Using AI Code Generation

copy

Full Screen

1var data = {2}3var xhr = new XMLHttpRequest();4xhr.setRequestHeader("Content-Type", "application/json");5xhr.onreadystatechange = function() {6 if (xhr.readyState == 4) {7 console.log(xhr.responseText);8 }9}10xhr.send(JSON.stringify(data));

Full Screen

Using AI Code Generation

copy

Full Screen

1var xhr = new XMLHttpRequest();2xhr.send();3var response = xhr.responseText;4console.log(response);5 return response.text();6}).then(function(text) {7 console.log(text);8});9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch();12 const page = await browser.newPage();13 const text = await page.evaluate(() => document.querySelector('h1').textContent);14 console.log(text);15 await browser.close();16})();17var page = require('webpage').create();18 var text = page.evaluate(function() {19 return document.querySelector('h1').textContent;20 });21 console.log(text);22 phantom.exit();23});24var casper = require('casper').create();25 var text = this.evaluate(function() {26 return document.querySelector('h1').textContent;27 });28 console.log(text);29});30casper.run();31from selenium import webdriver32from selenium.webdriver.common.keys import Keys33driver = webdriver.Firefox()34text = driver.find_element_by_tag_name('h1').text35print(text)36driver.quit()37import requests38print(r.text)39import urllib.request40html = response.read()41print(html)42import urllib243html = response.read()44print(html)45import urllib3

Full Screen

Using AI Code Generation

copy

Full Screen

1var xhr = require("wptoolkit").xhr;2 console.log(data);3});4var xhr = require("wptoolkit").xhr;5 headers: {6 }7}, function (data) {8 console.log(data);9});10var xhr = require("wptoolkit").xhr;11 headers: {12 }13}, function (data) {14 console.log(data);15});16var xhr = require("wptoolkit").xhr;17 console.log(data);18});19var xhr = require("wptoolkit").xhr;20 headers: {21 }22}, function (data) {23 console.log(data);24});25var xhr = require("wptoolkit").xhr;26 console.log(data);27});28var xhr = require("wptoolkit").xhr;29 console.log(data);30});31var xhr = require("wptoolkit").xhr;32 console.log(data);33});34var xhr = require("wptoolkit").xhr;35 headers: {36 }37}, function (data) {38 console.log(data);39});

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 wpt 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