Ajax-hook拦截所有的Ajax请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013628152/article/details/84076274

在解决同一个浏览器登录多个账户,解决sesson覆盖问题的时候,我想到的办法是为每一个用户的session定义唯一的key,例如“sessionUser”+accessToken.

accessToken是登录校验成功后,生成的唯一字符串,你可以使用UUID策略。这样,我需要给所有的ajax请求带上这个accessToken,有没有简单的办法,有的,Ajax-hook可以做到。

Ajax-hook使用场景:需要给所有ajax请求添加统一签名、需要统计某个接口被请求的次数、需要限制http请求的方法必须为get或post、需要分析别人网络协议等等。

Ajax-hook开源地址

/** 
 * intercept ajax request
 * */
!function (ob) {
    ob.hookAjax = function (funs) {
        window._ahrealxhr = window._ahrealxhr || XMLHttpRequest
        XMLHttpRequest = function () {
            this.xhr = new window._ahrealxhr;
            for (var attr in this.xhr) {
                var type = "";
                try {
                    type = typeof this.xhr[attr]
                } catch (e) {}
                if (type === "function") {
                    this[attr] = hookfun(attr);
                } else {
                    Object.defineProperty(this, attr, {
                        get: getFactory(attr),
                        set: setFactory(attr)
                    })
                }
            }
        }

        function getFactory(attr) {
            return function () {
                return this.hasOwnProperty(attr + "_")?this[attr + "_"]:this.xhr[attr];
            }
        }

        function setFactory(attr) {
            return function (f) {
                var xhr = this.xhr;
                var that = this;
                if (attr.indexOf("on") != 0) {
                    this[attr + "_"] = f;
                    return;
                }
                if (funs[attr]) {
                    xhr[attr] = function () {
                        funs[attr](that) || f.apply(xhr, arguments);
                    }
                } else {
                    xhr[attr] = f;
                }
            }
        }

        function hookfun(fun) {
            return function () {
                var args = [].slice.call(arguments)
                if (funs[fun] && funs[fun].call(this, args, this.xhr)) {
                    return;
                }
                return this.xhr[fun].apply(this.xhr, args);
            }
        }
        return window._ahrealxhr;
    }
    ob.unHookAjax = function () {
        if (window._ahrealxhr)  XMLHttpRequest = window._ahrealxhr;
        window._ahrealxhr = undefined;
    }
}(window);

使用方法:

hookAjax({
	onload:function(xhr) {
		
	},
	open:function(arg){
	    if (arg[1].indexOf('?') != -1) {
	        arg[1]+="&accessToken="+$("#accessToken").val();
	    }else {
	        arg[1]+="?accessToken="+$("#accessToken").val();
	    }
	}

});

猜你喜欢

转载自blog.csdn.net/u013628152/article/details/84076274
今日推荐