Created
August 8, 2025 09:59
-
-
Save WebReflection/b4199ea6c0dbd3dcb415444cb5e25122 to your computer and use it in GitHub Desktop.
The easiest way to fetch JSON data when CORS is not an option but JSONP is
This file contains hidden or 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
let p = 0; | |
const fetchp = (url, ..._) => { | |
const { promise, resolve, reject } = Promise.withResolvers(); | |
const src = new URL(url); | |
const callback = `__json${p++}`; | |
src.searchParams.set('callback', callback); | |
document.head.appendChild(Object.assign( | |
document.createElement('script'), | |
{ async: true, onerror: reject, src } | |
)); | |
globalThis[callback] = value => { | |
delete globalThis[callback]; | |
resolve(value); | |
}; | |
return promise; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: