63 lines
2.8 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.

// 跨域get请求 返回text
import UserScriptEngine from "../../enum/UserScriptEngine";
function COFetch(url, method = 'get', body = null) {
const engine = getScriptEngine();
switch (engine) {
case UserScriptEngine.RAW: {
return new Promise((_, reject) => {
console.error(`[wh] 跨域请求错误:${UserScriptEngine.RAW}环境下无法进行跨域请求`);
reject(`错误:${UserScriptEngine.RAW}环境下无法进行跨域请求`);
});
}
case UserScriptEngine.PDA: {
const {PDA_httpGet, PDA_httpPost} = window;
return method === 'get' ?
// get
new Promise((resolve, reject) => {
if (typeof PDA_httpGet !== 'function') {
console.error('[wh] 跨域请求错误PDA版本不支持');
reject('错误PDA版本不支持');
}
PDA_httpGet(url)
.catch(e => {
console.error('[wh] 网络错误', e);
reject(`[wh] 网络错误 ${e}`);
})
.then(res => resolve(res.responseText));
}) :
// post
new Promise((resolve, reject) => {
if (typeof PDA_httpPost !== 'function') {
console.error('[wh] 跨域请求错误PDA版本不支持');
reject('错误PDA版本不支持');
}
PDA_httpPost(url, {'content-type': 'application/json'}, body)
.catch(e => {
console.error('[wh] 网络错误', e);
reject(`[wh] 网络错误 ${e}`);
})
.then(res => resolve(res.responseText));
});
}
case UserScriptEngine.GM: {
return new Promise((resolve, reject) => {
if (typeof GM_xmlhttpRequest !== 'function') {
console.error('[wh] 跨域请求错误用户脚本扩展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)}`),
});
});
}
}
}
export default COFetch