Skip to content

Instantly share code, notes, and snippets.

@bpetlert
Created March 14, 2019 02:38
Show Gist options
  • Save bpetlert/84b5083df99c6dda59c04bd93cb520b8 to your computer and use it in GitHub Desktop.
Save bpetlert/84b5083df99c6dda59c04bd93cb520b8 to your computer and use it in GitHub Desktop.
Fetch JSONP using vanilla javascript
/**
* source: [Create GUID / UUID in JavaScript?, broofa]{@link https://stackoverflow.com/a/2117523}
*/
export function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16),
);
}
/**
* Fetch JSONP using vanilla javascript
* adapted from [Simple JSONP in vanilla JS, @michaelpumo]{@link https://gist.github.com/gf3/132080/110d1b68d7328d7bfe7e36617f7df85679a08968#gistcomment-2090652}
*
* @example
* // returns {"id":"123","user":"John"}
* fetchJSONP('https://jsfiddle.net/echo/jsonp?id=123&user=John').then(response => {
* response.json().then(data => {
* console.log(data);
* });
* });
*/
export function fetchJSONP(url) {
return new Promise(resolve => {
let script = document.createElement('script');
let uuid = uuidv4().replace(/-/g, '');
let name = `_jsonp_${uuid}`;
if (url.match(/\?/)) {
url += `&callback=${name}`;
} else {
url += `?callback=${name}`;
}
script.src = url;
window[name] = json => {
resolve(new Response(JSON.stringify(json)));
script.remove();
delete window[name];
};
document.body.appendChild(script);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment