-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrab.js
123 lines (101 loc) · 2.83 KB
/
grab.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
const grab = {
targetElement: null,
callback: null,
method: null,
url: null,
async: true,
xhr: new XMLHttpRequest(),
headers: null,
enableCors: false,
perform: function(method, url, async, enable) {
this.method = method;
this.url = url;
this.async = async;
this.xhr = new XMLHttpRequest();
this.cors(enable !== undefined ? enable : this.enableCors);
return this;
},
cors: function(enable) {
this.xhr.withCredentials = enable;
return this;
},
here: function(targetElement, responseType) {
this.targetElement = document.getElementById(targetElement);
this.callback = responseType;
return this;
},
setHeaders: function(headers) {
this.headers = headers;
return this;
},
setData: function(data) {
this.data = data;
return this;
},
error: function(callback) {
this.xhr.onerror = callback;
return this;
},
timeout: function(milliseconds, callback) {
this.xhr.timeout = milliseconds;
this.xhr.ontimeout = callback;
return this;
},
progress: function(callback) {
this.xhr.onprogress = callback;
return this;
},
responseType: function(type) {
this.xhr.responseType = type;
return this;
},
abort: function() {
this.xhr.abort();
console.log('Request aborted.');
return this;
},
cache: function(value) {
this.xhr.setRequestHeader('Cache-Control', value);
return this;
},
done: function() {
const self = this;
this.xhr.onload = function() {
self.handleResponse();
};
this.xhr.open(this.method, this.url, this.async);
if (this.xhr.withCredentials) {
console.log('CORS is enabled.');
} else {
console.log('CORS is disabled.');
}
if (this.headers) {
for (const [headerName, headerValue] of Object.entries(this.headers)) {
this.xhr.setRequestHeader(headerName, headerValue);
}
}
if (this.method.toUpperCase() === 'POST') {
if (!this.headers || !this.headers['Content-type']) {
console.error('Content type is not specified for POST request.');
return;
}
}
this.xhr.send(this.data);
},
handleResponse: function() {
const response = this.xhr.response;
if (this.targetElement) {
if (typeof this.callback === 'function') {
this.callback.call(this.targetElement, response);
} else if (this.callback === 'all') {
this.targetElement.innerHTML = response;
} else if (this.callback === 'header' && this.headers) {
for (const [headerName, headerValue] of Object.entries(this.headers)) {
const specificHeader = this.xhr.getResponseHeader(headerValue);
this.targetElement.innerHTML += `${headerName}: ${specificHeader || 'Header not found'}<br>`;
}
}
}
},
};
window.grab = grab;