我通过更改XMLHttpRequest.prototype打开和发送方法来拦截站点中的AJAX请求.在我测试的所有浏览器中,此方法都能正常工作.但是,当谈到iOS版Chrome(iPhone)时,该代码具有最奇怪的错误:就像它不断触发我在原型中更改的代码一样(显然崩溃了).
这是我正在做的一个极小的例子:
var open = XMLHttpRequest.prototype.open; // Caching the original
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
alert('open'); // Here is my code
open.call(this, method, url, async, user, pass); // Calling the original
};
我整理了一个JSBin,目的是可以在iOS上使用Chrome浏览器访问:Demo
根据this的答案,我正在使用的代码(基本上与该答案中的一个OP相同)是安全的,应该没有理由担心.而且,事实上,Chrome for iOS是唯一运行异常的浏览器.
这已经让我发狂了两天,任何建议或解决方法都值得赞赏.
解决方法:
如何在iOS版Chrome上拦截AJAX请求
这是适用于大多数浏览器的XMLHttpRequest拦截代码:
(function(open) {
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
// Intercept the open request here
alert("Intercepted: " + url);
open.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://google.com",true);
xmlhttp.send();
Chrome浏览器(iOS版)存在问题.它已经提出并在下面进行了研究.我将提供有关“重复的open()调用”错误的说明,演示和解决方法.
从上次参考:
On page load, Chrome makes two asynchronous requests to services that
it is presumably running locally. By the sound of the URLs it’s
requesting, these services are used to ensure the safety of the page
you are accessing.
这是Chrome尝试访问的一个此类本地URL的屏幕截图(Demo):
Chrome会定期自行调用XMLHttpRequest.open().这些对拦截代码的重复调用不是由拦截代码本身引起的.它们是由Chrome浏览器中不相关且重复的通话引起的.我已经确定了两个这样的URL.可能还有其他.
> / chromeforiossecurity / b86 … 98d /
> https://localhost:0/chromecheckurl
根据我的研究,这种解决方法可以使XMLHttpRequest代码拦截在iOS版Chrome上正常工作.请参阅此JSBin测试演示.它将演示这些重复调用也是如何发生的.本质上,拦截代码应忽略Chrome使用的URL.
(function(open) {
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
var d1 = document.getElementById('urls');
// Avoid intercepting Chrome on iOS local security check urls
if(url.indexOf("/chromecheckurl") < 0 && url.indexOf("/chrome") !== 0) {
// These are what we want to intercept
d1.insertAdjacentHTML('beforeend', ''+url+'
');
} else {
// These are the internal Chrome requests - we can ignore them
d1.insertAdjacentHTML('beforeend', ''+url+'
');
}
open.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://google.com",true);
xmlhttp.send();
这是我的最佳尝试,它解释了iOS版Chrome上的“重复open()调用”错误以及一种解决方法.
标签:ajax,chrome-ios,ios,javascript
来源: https://codeday.me/bug/20191120/2044861.html