我正在编写一个扩展,以使用户能够拦截任何ajax请求并让他们对其进行修改。下面的代码有效。它将拦截xmlhttprequest打开/发送并通过对话框提示我。问题是我在xmlhttprequest.open中使用了hint()而不是我期望它使用的hintOpen()方法。我想知道是否有人对我需要做什么才能使它起作用。
(function(){
async function promptSend(data){
return new Promise(function(resolve){
var swalConfig = {
html: `<textarea id="swal-input1" class="" rows="10" cols="50"></textarea><br><br>`,
focusConfirm: false,
preConfirm: () => {
resolve([document.getElementById("swal-input1").value])
},
onBeforeOpen: () => {
document.getElementById("swal-input1").value = data[0];
},
showCancelButton: false,
allowOutsideClick: false
};
try{
Swal.getQueueStep();
Swal.insertQueueStep(swalConfig)
}catch(e){
Swal.queue([swalConfig])
}
});
}
async function promptOpen(data){
return new Promise(function(resolve){
var swalConfig = {
html: `<label for='swal-input1'>Method</label><input name='swal-input1' id='swal-input1' style='width:100%'><br><br>`+
`<label for='swal-input2'>Url</label><input name='swal-input2' id='swal-input2' style='width:100%'>`,
focusConfirm: false,
preConfirm: () => {
resolve([document.getElementById("swal-input1").value,document.getElementById("swal-input2").value])
},
onBeforeOpen: () => {
document.getElementById("swal-input1").value = data[0];
document.getElementById("swal-input2").value = data[1];
},
showCancelButton: false,
allowOutsideClick: false
};
try{
Swal.getQueueStep();
Swal.insertQueueStep(swalConfig)
}catch(e){
Swal.queue([swalConfig])
}
})
}
// Intercepts all XmlHttpRequest.open calls
var proxiedOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
//let newArguments = await promptOpen(arguments)
arguments[0] = prompt("Enter Method",arguments[0])
arguments[1] = prompt("Enter Url",arguments[1])
return proxiedOpen.apply(this, [].slice.call(arguments));
}
// Intercepts all XmlHttpRequest.send calls
var proxiedSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = async function() {
let newArgument = await promptSend(arguments);
arguments[0] = newArgument[0];
return proxiedSend.apply(this, [].slice.call(arguments));
}
})()
任何尝试将其转换为promptOpen的尝试都会导致执行的ajax调用调用/ undefined或根本不调用。
我尝试了最明显的方法,即将其转变为异步函数,并使用了诸如xmlhttprequest.send的工作方式。
var proxiedOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = async function(method, url, async, user, password) {
let newArguments = await promptOpen(arguments)
arguments[0] = newArguments[0]
arguments[1] = newArguments[1]
return proxiedOpen.apply(this, [].slice.call(arguments));
}
但是正如我所说,它根本不执行任何ajax请求,甚至不提示xmlhttprequest.send框。