-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { jsonp } from './jsonp' | ||
import type { LoadResourceUrl } from './loadResource' | ||
|
||
jest.mock( | ||
'./loadResource', | ||
() => | ||
({ | ||
loadResource: (url: LoadResourceUrl) => { | ||
const _url = new URL(url.path) | ||
;(globalThis as any)[_url.searchParams.get('callback')!]?.(true) | ||
}, | ||
LoadResourceUrlType: {}, | ||
} as typeof import('./loadResource')), | ||
) | ||
|
||
describe('jsonp', () => { | ||
test('表现正常', async () => { | ||
expect(await jsonp('https://baidu.com/')).toBeTrue() | ||
}) | ||
}) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { loadResource, LoadResourceUrlType } from './loadResource' | ||
|
||
let i = 0 | ||
|
||
/** | ||
* 发起 jsonp 请求。 | ||
* | ||
* @param url 请求地址 | ||
* @param keyOfCallbackName 回调函数名的键 | ||
*/ | ||
export function jsonp<T>( | ||
url: string, | ||
keyOfCallbackName = 'callback', | ||
): Promise<T> { | ||
return new Promise<T>((resolve, reject) => { | ||
const callbackName = `__vtils_jsonp_callbacks__${i++}` | ||
;(window as any)[callbackName] = (result: T) => { | ||
resolve(result) | ||
delete (window as any)[callbackName] | ||
} | ||
const _url = new URL(url) | ||
_url.searchParams.set(keyOfCallbackName, callbackName) | ||
url = _url.toString() | ||
loadResource({ | ||
path: url, | ||
type: LoadResourceUrlType.js, | ||
}).catch(reject) | ||
}) | ||
} |