import UserScriptEngine from "../../enum/UserScriptEngine"; import getScriptEngine from "./getScriptEngine"; import log from "./log"; /** * @deprecated */ export default function COFetch(url: URL | string, method: 'get' | 'post' = 'get', body: any = null): Promise { return new Promise((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) }`), }); } } }); }