问题描述
我有我在tampermonkey上使用的脚本
const origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (...args) {
if (typeof args[1] === 'string')
args[1] = args[1].replace('example.com/*','mywebsite.com/*');
}
return origOpen.apply(this,args);
};
此脚本对特定的文件URL完全适用,但不适用于重定向URL下的所有路由。这不是为了完全重定向页面。我想知道如何将example.com
下发生的每个单个请求重定向到mywebsite.com
。
解决方法
两个问题
问题1。
大多数请求可能不是通过完整URL发起的。因此,您将收到/api/something.json
之类的请求,而这些请求不会被替换。
您可以使用URL
对象处理所有情况。
const origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (...args) {
if (typeof args[1] === 'string') {
// will use example.com as a base if path is relative,ignore it if not
const newURL = new URL(args[1],"http://www.example.com");
newURL.host = "mywebsite.xxx";
args[1] = newURL+"";
}
return origOpen.apply(this,args);
};
问题2。
XMLHttpRequest
不是获取AJAX数据的唯一方法。还可以考虑以类似方式替换fetch
异步函数。