(
url: string,
opts: {
type: 'fetch' | 'GM_xmlhttpRequest';
method?: 'get' | 'post' | 'head';
responseType?: T;
headers?: Record<string, string>;
data?: Record<string, any>;
}
)
| 6 | * @param opts 请求参数 |
| 7 | */ |
| 8 | export function request<T extends 'json' | 'text'>( |
| 9 | url: string, |
| 10 | opts: { |
| 11 | type: 'fetch' | 'GM_xmlhttpRequest'; |
| 12 | method?: 'get' | 'post' | 'head'; |
| 13 | responseType?: T; |
| 14 | headers?: Record<string, string>; |
| 15 | data?: Record<string, any>; |
| 16 | } |
| 17 | ): Promise<T extends 'json' ? any : string> { |
| 18 | return new Promise((resolve, reject) => { |
| 19 | try { |
| 20 | /** 默认参数 */ |
| 21 | const { responseType = 'json', method = 'get', type = 'fetch', data = {}, headers = {} } = opts || {}; |
| 22 | /** 环境变量 */ |
| 23 | const env = $.isInBrowser() ? 'browser' : 'node'; |
| 24 | |
| 25 | /** 如果是跨域模式并且是浏览器环境 */ |
| 26 | if (type === 'GM_xmlhttpRequest' && env === 'browser') { |
| 27 | if (typeof GM_xmlhttpRequest !== 'undefined') { |
| 28 | const contentType = headers['Content-Type'] || headers['content-type']; |
| 29 | const requestData = |
| 30 | contentType === 'application/x-www-form-urlencoded' |
| 31 | ? new URLSearchParams(data).toString() |
| 32 | : Object.keys(data).length |
| 33 | ? JSON.stringify(data) |
| 34 | : undefined; |
| 35 | // eslint-disable-next-line no-undef |
| 36 | GM_xmlhttpRequest({ |
| 37 | url, |
| 38 | method: method.toUpperCase() as 'GET' | 'HEAD' | 'POST', |
| 39 | data: requestData, |
| 40 | headers: Object.keys(headers).length ? headers : undefined, |
| 41 | responseType: responseType === 'json' ? 'json' : undefined, |
| 42 | onload: (response) => { |
| 43 | if (response.status === 200) { |
| 44 | if (responseType === 'json') { |
| 45 | try { |
| 46 | resolve(JSON.parse(response.responseText)); |
| 47 | } catch (error) { |
| 48 | reject(error); |
| 49 | } |
| 50 | } else { |
| 51 | resolve(response.responseText || ''); |
| 52 | } |
| 53 | } else { |
| 54 | reject(response.responseText); |
| 55 | } |
| 56 | }, |
| 57 | onerror: (err) => { |
| 58 | console.error('GM_xmlhttpRequest error', err); |
| 59 | reject(err); |
| 60 | } |
| 61 | }); |
| 62 | } else { |
| 63 | reject(new Error('GM_xmlhttpRequest is not defined')); |
| 64 | } |
| 65 | } else { |
no test coverage detected