import _debug from 'debug'; import { nanoid } from 'nanoid'; let count = 0; const noop = () => {}; const debug = _debug('jsonp'); /** * JSONP handler * * Options: * - param {String} qs parameter (`callback`) * - prefix {String} qs parameter (`__jp`) * - name {String} qs parameter (`prefix` + incr) * - timeout {Number} how long after a timeout error is emitted (`60000`) * * @param {String} url * @param {Object|Function} optional options / callback * @param {Function} optional callback */ export default (url, opts, fn) => { if ('function' == typeof opts) { fn = opts; opts = {}; } const _root: any = window; if (!opts) opts = {}; var prefix = opts.prefix || '__jp'; // use the callback name that was passed if one was provided. // otherwise generate a unique name by incrementing our counter. var id = opts.name || prefix + nanoid(3) + count++; var param = opts.param || 'callback'; var timeout = null != opts.timeout ? opts.timeout : 60000; var enc = encodeURIComponent; var target: any = document.getElementsByTagName('script')[0] || document.head; var script; var timer; if (timeout) { timer = setTimeout(function () { cleanup(); if (fn) fn(new Error('Timeout')); }, timeout); } function cleanup() { if (script.parentNode) script.parentNode.removeChild(script); _root[id] = noop; if (timer) clearTimeout(timer); } function cancel() { if (_root[id]) { cleanup(); } } _root[id] = function (data) { debug('jsonp got', data); cleanup(); if (fn) fn(null, data); }; // add qs component url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id); url = url.replace('?&', '?'); debug('jsonp req "%s"', url); // create script script = document.createElement('script'); script.src = url; target.parentNode.insertBefore(script, target); return cancel; };