-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path请求代理.user.ts
65 lines (65 loc) · 2.07 KB
/
请求代理.user.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// ==UserScript==
// @name 请求代理
// @namespace http://tampermonkey.net/
// @version 1.0.2
// @description 请求代理,可以修改任意请求的url
// @author 崮生 [email protected]
// @include *
// @grant unsafeWindow
// @grant GM.setValue
// @grant GM.getValue
// @grant GM.xmlHttpRequest
// @run-at document-start
// @connect shenzilong.cn
// ==/UserScript==
import App from "./request_agent_interface.svelte";
//@ts-ignore
typeof unsafeWindow === "undefined" ? (window.unsafeWindow = window) : (window = unsafeWindow);
import { proxy } from "ajax-hook";
(async function () {
let Xhr = window.XMLHttpRequest;
let urlHandler = (url: string) => url;
proxy({
//请求发起前进入
onRequest: (config: any, handler: any) => {
console.log("[💚开始请求]", config.url, urlHandler(config.url));
config.url = urlHandler(config.url);
/** 关闭 withCredentials 避免触发跨域 */
config.withCredentials = false;
handler.next(config);
},
//请求发生错误时进入,比如超时;注意,不包括http状态码错误,如404仍然会认为请求成功
onError: (err: any, handler: any) => {
handler.next(err);
},
//请求成功后进入
onResponse: (response: any, handler: any) => {
handler.next(response);
},
});
/** 替换 XMLHttpRequest */
window.XMLHttpRequest = XMLHttpRequest;
document.createElementNS("http://www.w3.org/1999/xhtml", "div");
const app_div = document.createElement("div");
setTimeout(() => {
document.body.appendChild(app_div);
}, 1000);
let defaultCode = `(url) => {
return "" + url;
}`;
const code = localStorage.getItem("urlHandler") || defaultCode;
setProcessingMethod(eval(code));
const app = new App({
target: app_div,
props: {
setProcessingMethod,
defaultCode: code,
},
});
function setProcessingMethod(handler: typeof urlHandler, code?: string) {
urlHandler = handler;
if (code) {
localStorage.setItem("urlHandler", code);
}
}
})();