Skip to content

Commit

Permalink
feat(utils): 新增 jsonp 发起 jsonp 请求
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 29, 2021
1 parent d2a93d8 commit 1c2ae89
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export * from './isPossibleChineseMobilePhoneNumber'
export * from './isPromiseLike'
export * from './isType'
export * from './isUrl'
export * from './jsonp'
export * from './keysStrict'
export * from './loadCss'
export * from './loadResource'
Expand Down
20 changes: 20 additions & 0 deletions src/utils/jsonp.test.ts
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()
})
})
29 changes: 29 additions & 0 deletions src/utils/jsonp.ts
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)
})
}

0 comments on commit 1c2ae89

Please sign in to comment.