如何截取不同的JS库的所有AJAX请求 [英] How to intercept all AJAX requests made by different JS libraries

查看:169
本文介绍了如何截取不同的JS库的所有AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是建设有不同的JS库的web应用程序(AngularJS,的OpenLayers,...),并需要一种方法来拦截所有的Ajax响应可以,如果登录用户会话过期(响应回来与 401未授权状态),重定向他到登录页面。

I am building a web app with different JS libraries (AngularJS, OpenLayers,...) and need a way to intercept all AJAX responses to be able, in case the logged user session expired (response gets back with 401 Unauthorized status), to redirect him to the login page.

我知道AngularJS报价拦截来管理这样的情景,但没有能够找到一种方法来实现这种注入的OpenLayers请求。所以,我选择了一个香草JS的方法。

I know AngularJS offers interceptors to manage such scenarios, but wasn't able to find a way to achieve such injection into OpenLayers requests. So I opted for a vanilla JS approach.

这里我发现这块code ...

Here I found this piece of code...

(function(open) {

    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {

        this.addEventListener("readystatechange", function() {
            console.log(this.readyState); // this one I changed
        }, false);

        open.call(this, method, url, async, user, pass);
    };

})(XMLHttpRequest.prototype.open);

...这是我适应和看起来像它的行为与预期(仅测试了最后的谷歌浏览器)。

...which I adapted and looks like it behaves as expected (only tested it on last Google Chrome).

由于它会修改XMLHTT prequest原型我想知道这是如何造成的危险,或者它可能会产生严重的性能问题。顺便说一下会不会有任何有效的替代方案?

As it modifies the prototype of XMLHTTPRequest I am wondering how dangerous this could result or if it could produce serious performance issues. And by the way would there be any valid alternative?

推荐答案

这类型的函数挂钩是完全安全的,并定期对等方法进行其他原因而作出的。

This type of function hooking is perfectly safe and is done regularly on other methods for other reasons.

和,唯一的性能影响真的只有一个额外的函数调用每个。开()加任何code执行自己这可能是无关紧要的,当网络电话参与。

And, the only performance impact is really only one extra function call for each .open() plus whatever code you execute yourself which is probably immaterial when a networking call is involved.

在IE浏览器,这样就再也抓不到code,尝试使用的ActiveXObject 控制做的Ajax方法。写得code首先查找了 XMLHtt prequest 对象,并使用,如果可用,并且自IE 7已经可用,但是,可能会有一些$使用了的ActiveXObject 方法(如果可用)这将通过更晚版本的IE是真实的。

In IE, this won't catch any code that tries to use the ActiveXObject control method of doing Ajax. Well written code looks first for the XMLHttpRequest object and uses that if available and that has been available since IE 7. But, there could be some code that uses the ActiveXObject method if it's available which would be true through much later versions of IE.

这篇关于如何截取不同的JS库的所有AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆