Javascript 在提升负载之前拦截了XHR-运行函数
在带有扩展注入自定义Javascript 在提升负载之前拦截了XHR-运行函数,javascript,html,google-chrome-extension,xmlhttprequest,Javascript,Html,Google Chrome Extension,Xmlhttprequest,在带有扩展注入自定义XMLHttpRequest类的网页上,我需要在文档其余部分引发load事件之前拦截并修改某些响应。现在,我的修改代码对加载事件作出反应。在触发load事件之前,如何使用函数修改响应 这是我正在使用的代码: 让oldXHROpen=window.XMLHttpRequest.prototype.open; window.XMLHttpRequest.prototype.open=函数(方法、url、异步、用户、密码){ var originalresp=此; //对方法、ur
XMLHttpRequest
类的网页上,我需要在文档其余部分引发load
事件之前拦截并修改某些响应。现在,我的修改代码对加载事件作出反应。在触发load
事件之前,如何使用函数修改响应
这是我正在使用的代码:
让oldXHROpen=window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open=函数(方法、url、异步、用户、密码){
var originalresp=此;
//对方法、url等做些什么。
原始响应addEventListener('load',异步函数(){
//对回复文本做些什么
//***在引发文档其余部分的加载之前,需要执行此函数***
value='这是一个测试XML文档';
parser=新的DOMParser();
apiresponsexml=parser.parseFromString(值为'application/xml');
//替换响应中的数据
对象。定义属性(原始响应{
‘回应’:{
价值:价值
},
“responseXML”:{
值:apiresponsexml,
},
“responseText”:{
价值:价值,
}
});
});
返回oldXHROpen.apply(原始响应、参数);
};
此问题是
send()
内部的.Overrideonreadystatechange
(加载/加载前激发)的继续:
由于其他扩展或页面脚本也可能钩住XHR,因此在内容脚本中运行您的代码时使用。谢谢!当我有更多的时间添加其他代码时,我会尝试一下。
function plantXhrHook() {
let origStateChange;
function modifyResponse(e) {
if (this.readyState === 4) {
const value = 'foo';
let xml;
Object.defineProperties(this, {
response: {value},
responseText: {value},
responseXML: {
get() {
if (typeof xml === 'undefined')
xml = new DOMParser().parseFromString(value, 'application/xml');
return xml;
},
},
});
}
if (origStateChange) {
origStateChange.apply(this, arguments);
}
};
const origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function () {
origStateChange = this.onreadystatechange;
this.onreadystatechange = modifyResponse;
origSend.apply(this, arguments);
};
}
const script = document.createElement('script');
script.textContent = `(${plantXhrHook})()`;
document.documentElement.appendChild(script);
script.remove();