2022-10-09 17:56:16 +08:00

66 lines
2.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import UserScriptEngine from "../../../enum/UserScriptEngine";
import getScriptEngine from "./getScriptEngine";
import Log from "../../../class/Log";
/**
* @deprecated
*/
export default function COFetch(url: URL | string, method: 'get' | 'post' = 'get', body: any = null): Promise<string> {
return new Promise<string>((resolve, reject) => {
const engine = getScriptEngine();
switch (engine) {
case UserScriptEngine.RAW: {
console.error(`[wh] 跨域请求错误:${ UserScriptEngine.RAW }环境下无法进行跨域请求`);
reject(`错误:${ UserScriptEngine.RAW }环境下无法进行跨域请求`);
break;
}
case UserScriptEngine.PDA: {
const { PDA_httpGet, PDA_httpPost } = window;
// get
if (method === 'get') {
if (typeof PDA_httpGet !== 'function') {
Log.error('COFetch网络错误PDA版本不支持');
reject('COFetch网络错误PDA版本不支持');
}
PDA_httpGet(url)
.then(res => resolve(res.responseText))
.catch(e => {
Log.error('COFetch网络错误', e);
reject(`COFetch网络错误 ${ e }`);
})
}
// post
else {
if (typeof PDA_httpPost !== 'function') {
Log.error('COFetch网络错误PDA版本不支持');
reject('COFetch网络错误PDA版本不支持');
}
PDA_httpPost(url, { 'content-type': 'application/json' }, body)
.then(res => resolve(res.responseText))
.catch(e => {
Log.error('COFetch网络错误', e);
reject(`COFetch网络错误 ${ e }`);
});
}
break;
}
case UserScriptEngine.GM: {
let { GM_xmlhttpRequest } = window;
if (typeof GM_xmlhttpRequest !== 'function') {
Log.error('COFetch网络错误用户脚本扩展API错误');
reject('错误用户脚本扩展API错误');
}
GM_xmlhttpRequest({
method: method,
url: url,
data: method === 'get' ? null : body,
headers: method === 'get' ? null : { 'content-type': 'application/json' },
onload: res => resolve(res.response),
onerror: res => reject(`连接错误 ${ JSON.stringify(res) }`),
ontimeout: res => reject(`连接超时 ${ JSON.stringify(res) }`),
});
}
}
});
}