-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonp.js
executable file
·54 lines (45 loc) · 1.21 KB
/
jsonp.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
//
const config = {
callback: 'callback',
}
function generateCB() {
return `jsonp${Math.ceil(Math.random() * 1000000)}`;
}
function removeCB(_name) {
try {
delete window[_name];
} catch (e) {
window[_name] = undefined;
}
}
function createScript(_url, _id) {
const script = document.createElement('script');
script.setAttribute('src', _url);
script.id = _id;
document.getElementsByTagName('head')[0].appendChild(script);
}
function removeScipt(_id) {
const script = document.getElementById(_id);
document.getElementsByTagName('head')[0].removeChild(script);
}
function fetchJsonp(_url, params = {}, options = {}) {
return new Promise((resolve, reject) => {
const jsonp = options.callback || config.callback,
cb = generateCB(), // get callback function name
scriptId = cb;
let query = [];
Object.keys(params).forEach(key => {
query.push(`${key}=${params[key]}`);
})
_url += (query.elngth === 0) ? '?' : `?${query.join('&')}`;
_url += `&${jsonp}=${cb}`;
// register the callback function
window[cb] = (res) => {
resolve(res);
removeScipt(scriptId);
removeCB(cb);
}
createScript(_url, scriptId);
})
}
export default fetchJsonp