xhr_sharedworker.js (2600B)
1 /** 2 * Any copyright is dedicated to the Public Domain. 3 * http://creativecommons.org/publicdomain/zero/1.0/ 4 */ 5 6 /* eslint-env worker */ 7 onconnect = e => { 8 e.ports[0].onmessage = event => { 9 const url = event.data; 10 11 var xhr = new XMLHttpRequest(); 12 xhr.open("GET", url, false); 13 xhr.send(); 14 15 const refText = xhr.responseText; 16 17 function getResponse(type) { 18 xhr = new XMLHttpRequest(); 19 xhr.open("GET", url, false); 20 if (type !== undefined) { 21 xhr.responseType = type; 22 } 23 xhr.send(); 24 return xhr.response; 25 } 26 27 if (getResponse() != refText) { 28 throw new Error("unset responseType failed"); 29 } 30 31 if (getResponse("") != refText) { 32 throw new Error("'' responseType failed"); 33 } 34 35 if (getResponse("text") != refText) { 36 throw new Error("'text' responseType failed"); 37 } 38 39 var array = new Uint8Array(getResponse("arraybuffer")); 40 if (String.fromCharCode.apply(String, array) != refText) { 41 throw new Error("'arraybuffer' responseType failed"); 42 } 43 44 var blob = getResponse("blob"); 45 if (new FileReaderSync().readAsText(blob) != refText) { 46 throw new Error("'blob' responseType failed"); 47 } 48 49 // Make sure that we get invalid state exceptions when getting the wrong 50 // property. 51 52 function testResponseTextException(type) { 53 xhr = new XMLHttpRequest(); 54 xhr.open("GET", url, false); 55 xhr.responseType = type; 56 xhr.send(); 57 58 var exception; 59 60 try { 61 xhr.responseText; 62 } catch (ex) { 63 exception = ex; 64 } 65 66 if (!exception) { 67 throw new Error( 68 `Failed to throw when getting responseText on ${type} type` 69 ); 70 } 71 72 if (exception.name != "InvalidStateError") { 73 throw new Error( 74 `Unexpected error when getting responseText on ${type} type` 75 ); 76 } 77 78 if (exception.code != DOMException.INVALID_STATE_ERR) { 79 throw new Error( 80 `Unexpected error code when getting responseText on ${type} type` 81 ); 82 } 83 } 84 85 testResponseTextException("arraybuffer"); 86 testResponseTextException("blob"); 87 88 // Make sure "document" works, but returns text. 89 xhr = new XMLHttpRequest(); 90 91 if (xhr.responseType != "") { 92 throw new Error("Default value for responseType is wrong!"); 93 } 94 95 xhr.open("GET", url, false); 96 xhr.responseType = "document"; 97 xhr.send(); 98 99 if (xhr.responseText != refText) { 100 throw new Error("'document' type not working correctly"); 101 } 102 103 e.ports[0].postMessage("done"); 104 }; 105 };