Last active
February 3, 2023 02:08
-
-
Save dragon-fish/a88c843ea7190fc43d0cfc3108a4b1db to your computer and use it in GitHub Desktop.
A very simple JSONP package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A very simple JSONP package | |
* @author Dragon-Fish | |
* @license MIT | |
*/ | |
/** | |
* jsonp | |
* @example | |
* ```ts | |
* jsonp('https://zh.wikipedia.org/w/api.php', { | |
* action: 'query', | |
* format: 'json', | |
* }).then(console.info) | |
* ``` | |
*/ | |
export async function jsonp<T = any>( | |
endpoint: string, | |
params: Record<string, string> = {}, | |
options?: { cbParamName: string } | |
): Promise<T> { | |
const url = new URL(endpoint) | |
const cbParamName = options?.cbParamName || 'callback' | |
let cbFnName = params[cbParamName] | |
if (!cbFnName) { | |
cbFnName = params[cbParamName] = | |
'JSONP_' + Math.random().toString(16).slice(2) | |
} | |
url.search = '' + new URLSearchParams(params) | |
const script = document.createElement('script') | |
return new Promise<T>((resolve, reject) => { | |
;(window as any)[cbFnName] = (data: T) => resolve(data) | |
script.src = '' + url | |
document.body.appendChild(script) | |
script.addEventListener('error', (e) => { | |
reject(e) | |
}) | |
}).finally(() => { | |
document.body.removeChild(script) | |
delete (window as any)[cbFnName] | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment