forked from cheeaun/hackerweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhnapi-worker.js
44 lines (43 loc) · 986 Bytes
/
hnapi-worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
var requests = {};
addEventListener('message', function(e){
var data = e.data,
url = data.url,
timeout = data.timeout || 20000;
var r = requests[url] || new XMLHttpRequest();
if (r._timeout) clearTimeout(r._timeout);
r._timeout = setTimeout(function(){
r.abort();
}, timeout);
r.onload = function(){
clearTimeout(this._timeout);
delete requests[url];
var response;
try {
response = JSON.parse(this.responseText);
} catch (e){}
if (this.status == 200 && response && !response.error){
postMessage({
url: url,
response: response
});
} else {
postMessage({
url: url,
error: true
});
}
};
r.onerror = r.onabort = r.ontimeout = function(e){
clearTimeout(this._timeout);
delete requests[url];
postMessage({
url: url,
error: JSON.parse(JSON.stringify(e))
});
}
if (r.readyState <= 1){
r.open('GET', url + '?' + (+new Date()), true);
r.send();
}
requests[url] = r;
});