-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEverything-Hook.js
More file actions
2242 lines (2200 loc) · 86.5 KB
/
Everything-Hook.js
File metadata and controls
2242 lines (2200 loc) · 86.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Everything-Hook
// @namespace https://gitee.com/HGJing/everthing-hook/
// @updateURL https://gitee.com/HGJing/everthing-hook/raw/master/src/everything-hook.js
// @version 0.5.9056
// @include *
// @description it can hook everything
// @author Cangshi
// @match http://*/*
// @grant none
// @run-at document-start
// ==/UserScript==
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else {
var a = factory();
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ([
/* 0 */
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/**
* ---------------------------
* Time: 2017/9/20 18:33.
* Author: Cangshi
* View: http://palerock.cn
* ---------------------------
*/
const eUtils = __webpack_require__(1);
~(function (global, factory) {
"use strict";
if ( true && typeof module.exports === "object") {
var results = factory.bind(global)(global, eUtils, true) || [];
var HookJS = {};
results.forEach(function (part) {
HookJS[part.name] = part.module;
});
module.exports = HookJS;
} else {
factory.bind(global)(global, eUtils);
}
}(typeof window !== "undefined" ? window : this, function (_global, utils, noGlobal) {
/**
* @namespace EHook
* @author Cangshi
* @constructor
* @see {@link https://palerock.cn/projects/006HDUuOhBj}
* @license Apache License 2.0
*/
var EHook = function () {
var _autoId = 1;
var _hookedMap = {};
var _hookedContextMap = {};
this._getHookedMap = function () {
return _hookedMap;
};
this._getHookedContextMap = function () {
return _hookedContextMap;
};
this._getAutoStrId = function () {
return '__auto__' + _autoId++;
};
this._getAutoId = function () {
return _autoId++;
};
};
EHook.prototype = {
/**
* Get a hook id for an object; create one if missing
* @param context
* @return {*}
* @private
*/
_getHookedId: function (context) {
var contextMap = this._getHookedContextMap();
var hookedId = null;
Object.keys(contextMap).forEach(key => {
if (context === contextMap[key]) {
hookedId = key;
}
});
if (hookedId == null) {
hookedId = this._getAutoStrId();
contextMap[hookedId] = context;
}
return hookedId;
},
/**
* Get the hook-method map for an object; create if missing
* @param context
* @return {*}
* @private
*/
_getHookedMethodMap: function (context) {
var hookedId = this._getHookedId(context);
var hookedMap = this._getHookedMap();
var thisTask = hookedMap[hookedId];
if (!utils.isExistObject(thisTask)) {
thisTask = hookedMap[hookedId] = {};
}
return thisTask;
},
/**
* Get the prototype hook task for the method; initialize if missing
* @param context
* @param methodName
* @private
*/
_getHookedMethodTask: function (context, methodName) {
var thisMethodMap = this._getHookedMethodMap(context);
var thisMethod = thisMethodMap[methodName];
if (!utils.isExistObject(thisMethod)) {
thisMethod = thisMethodMap[methodName] = {
original: undefined,
replace: undefined,
task: {
before: [],
current: undefined,
after: []
}
};
}
return thisMethod;
},
/**
* Execute multiple methods and inject a method and argument set
* @param context
* @param methods
* @param args
* @return result The last non-null return value from executed methods
* @private
*/
_invokeMethods: function (context, methods, args) {
if (!utils.isArray(methods)) {
return;
}
var result = null;
utils.ergodicArrayObject(context, methods, function (_method) {
if (!utils.isFunction(_method.method)) {
return;
}
var r = _method.method.apply(this, args);
if (r != null) {
result = r;
}
});
return result;
},
/**
* Build and replace the hooked method
* @param parent
* @param context
* @param methodName {string}
* @private
*/
_hook: function (parent, methodName, context) {
if (context === undefined) {
context = parent;
}
var method = parent[methodName];
var methodTask = this._getHookedMethodTask(parent, methodName);
if (!methodTask.original) {
methodTask.original = method;
}
if (utils.isExistObject(methodTask.replace) && utils.isFunction(methodTask.replace.method)) {
parent[methodName] = methodTask.replace.method(methodTask.original);
return;
}
var invokeMethods = this._invokeMethods;
// Assemble the hooked function
var builder = new utils.FunctionBuilder(function (v) {
return {
result: undefined
};
});
if (methodTask.task.before.length > 0) {
builder.push(function (v) {
invokeMethods(context || v.this, methodTask.task.before, [methodTask.original, v.arguments]);
});
}
if (utils.isExistObject(methodTask.task.current) && utils.isFunction(methodTask.task.current.method)) {
builder.push(function (v) {
return {
result: methodTask.task.current.method.call(context || v.this, parent, methodTask.original, v.arguments)
}
});
} else {
builder.push(function (v) {
return {
result: methodTask.original.apply(context || v.this, v.arguments)
}
});
}
if (methodTask.task.after.length > 0) {
builder.push(function (v) {
var args = [];
args.push(methodTask.original);
args.push(v.arguments);
args.push(v.result);
var r = invokeMethods(context || v.this, methodTask.task.after, args);
return {
result: (r != null ? r : v.result)
};
});
}
builder.push(function (v) {
return {
returnValue: v.result
};
});
// var methodStr = '(function(){\n';
// methodStr = methodStr + 'var result = undefined;\n';
// if (methodTask.task.before.length > 0) {
// methodStr = methodStr + 'invokeMethods(context, methodTask.task.before,[methodTask.original, arguments]);\n';
// }
// if (utils.isExistObject(methodTask.task.current) && utils.isFunction(methodTask.task.current.method)) {
// methodStr = methodStr + 'result = methodTask.task.current.method.call(context, parent, methodTask.original, arguments);\n';
// } else {
// methodStr = methodStr + 'result = methodTask.original.apply(context, arguments);\n';
// }
// if (methodTask.task.after.length > 0) {
// methodStr = methodStr + 'var args = [];args.push(methodTask.original);args.push(arguments);args.push(result);\n';
// methodStr = methodStr + 'var r = invokeMethods(context, methodTask.task.after, args);result = (r!=null?r:result);\n';
// }
// methodStr = methodStr + 'return result;\n})';
// Bind the hooked function
var resultFunc = builder.result();
for (var proxyName in methodTask.original) {
Object.defineProperty(resultFunc, proxyName, {
get: function () {
return methodTask.original[proxyName];
},
set: function (v) {
methodTask.original[proxyName] = v;
}
})
}
resultFunc.prototype = methodTask.original.prototype;
parent[methodName] = resultFunc;
},
/**
* Hook a method
* @inner
* @memberOf EHook
* @param parent{Object} The object that owns the method
* @param methodName{String} The method name
* @param config{Object} Hook configuration
*/
hook: function (parent, methodName, config) {
var hookedFailure = -1;
// Call context
var context = config.context !== undefined ? config.context : parent;
if (parent[methodName] == null) {
parent[methodName] = function () {
}
}
if (!utils.isFunction(parent[methodName])) {
return hookedFailure;
}
var methodTask = this._getHookedMethodTask(parent, methodName);
var id = this._getAutoId();
if (utils.isFunction(config.replace)) {
methodTask.replace = {
id: id,
method: config.replace
};
hookedFailure = 0;
}
if (utils.isFunction(config.before)) {
methodTask.task.before.push({
id: id,
method: config.before
});
hookedFailure = 0;
}
if (utils.isFunction(config.current)) {
methodTask.task.current = {
id: id,
method: config.current
};
hookedFailure = 0;
}
if (utils.isFunction(config.after)) {
methodTask.task.after.push({
id: id,
method: config.after
});
hookedFailure = 0;
}
if (hookedFailure === 0) {
this._hook(parent, methodName, context);
return id;
} else {
return hookedFailure;
}
},
/**
* Hook-replace a method
* @see Note: This will overwrite all previous hooks on the target method. It cannot be reused and cannot coexist with hookAfter, hookCurrent, or hookBefore. If used together, hookReplace takes precedence.
* @inner
* @memberOf EHook
* @param parent{Object} The object that owns the method
* @param context{Object=} Callback context
* @param methodName{String} The method name
* @param replace {function} Callback whose return value is the replacement function. Callback signature and return: [ method: original method, type:function return: the replacement function, type:function ]
* @return {number} Hook id
*/
hookReplace: function (parent, methodName, replace, context) {
return this.hook(parent, methodName, {
replace: replace,
context: context
});
},
/**
* Execute before the specified method
* @inner
* @memberOf EHook
* @param parent{Object} The object that owns the method
* @param methodName{String} The method name
* @param before{function} Callback executed before the original method. Callback params: [ method: original method, args: original method arguments (mutations affect subsequent call) ]
* @param context{Object=} Callback context
* @returns {number} Hook id (for unhook)
*/
hookBefore: function (parent, methodName, before, context) {
return this.hook(parent, methodName, {
before: before,
context: context
});
},
/**
* Intercept method execution; the original method will not run and is replaced by the provided current callback
* @see Note: Only one current hook is allowed per method; adding another overwrites the previous one. Can coexist with hookBefore/hookAfter.
* @inner
* @memberOf EHook
* @param parent{Object} The object that owns the method
* @param methodName{String} The method name
* @param current{function} Callback executed when the method is called. Params/return: [ parent: owner object, type:object; method: original method, type:function; args: arguments, type:array; return: value returned by the hooked method, type:* ]
* @param context{Object=} Callback context
* @returns {number} Hook id (for unhook)
*/
hookCurrent: function (parent, methodName, current, context) {
return this.hook(parent, methodName, {
current: current,
context: context
});
},
/**
* Execute after the specified method
* @inner
* @memberOf EHook
* @param parent{Object} The object that owns the method
* @param methodName{String} The method name
* @param after{function} Callback executed after the original method. Params/return: [ method: original method, type:function; args: original arguments, type:array; result: original return value, type:*; return: override return value, type:* ]
* @param context{Object=} Callback context
* @returns {number} Hook id (for unhook)
*/
hookAfter: function (parent, methodName, after, context) {
return this.hook(parent, methodName, {
after: after,
context: context
});
},
hookClass: function (parent, className, replace, innerName, excludeProperties) {
var _this = this;
var originFunc = parent[className];
if (!excludeProperties) {
excludeProperties = [];
}
excludeProperties.push('prototype');
excludeProperties.push('caller');
excludeProperties.push('arguments');
innerName = innerName || '_innerHook';
var resFunc = function () {
this[innerName] = new originFunc();
replace.apply(this, arguments);
};
this.hookedToString(originFunc, resFunc);
this.hookedToProperties(originFunc, resFunc, true, excludeProperties);
var prototypeProperties = Object.getOwnPropertyNames(originFunc.prototype);
var prototype = resFunc.prototype = {
constructor: resFunc
};
prototypeProperties.forEach(function (name) {
if (name === 'constructor') {
return;
}
var method = function () {
if (originFunc.prototype[name] && utils.isFunction(originFunc.prototype[name])) {
return originFunc.prototype[name].apply(this[innerName], arguments);
}
return undefined;
};
_this.hookedToString(originFunc.prototype[name], method);
prototype[name] = method;
});
this.hookReplace(parent, className, function () {
return resFunc;
}, parent)
},
hookedToProperties: function (originObject, resultObject, isDefined, excludeProperties) {
var objectProperties = Object.getOwnPropertyNames(originObject);
objectProperties.forEach(function (property) {
if (utils.contains(excludeProperties, property)) {
return;
}
if (!isDefined) {
resultObject[property] = originObject[property];
} else {
Object.defineProperty(resultObject, property, {
configurable: false,
enumerable: false,
value: originObject[property],
writable: false
});
}
});
},
hookedToString: function (originObject, resultObject) {
Object.defineProperties(resultObject, {
toString: {
configurable: false,
enumerable: false,
value: originObject.toString.bind(originObject),
writable: false
},
toLocaleString: {
configurable: false,
enumerable: false,
value: originObject.toLocaleString.bind(originObject),
writable: false
}
})
},
/**
* Hook global XMLHttpRequest (AJAX)
* @inner
* @memberOf EHook
* @param methods {object} Hook callbacks
* @return {*|number} Hook id
*/
hookAjax: function (methods) {
if (this.isHooked(_global, 'XMLHttpRequest')) {
return;
}
var _this = this;
var hookMethod = function (methodName) {
if (utils.isFunction(methods[methodName])) {
// Hook the original method before execution
_this.hookBefore(this.xhr, methodName, methods[methodName]);
}
// Return the bound internal xhr method
return this.xhr[methodName].bind(this.xhr);
};
var getProperty = function (attr) {
return function () {
return this.hasOwnProperty(attr + "_") ? this[attr + "_"] : this.xhr[attr];
};
};
var setProperty = function (attr) {
return function (f) {
var xhr = this.xhr;
var that = this;
if (attr.indexOf("on") !== 0) {
this[attr + "_"] = f;
return;
}
if (methods[attr]) {
xhr[attr] = function () {
f.apply(xhr, arguments);
};
// Hook on* methods when set
_this.hookBefore(xhr, attr, methods[attr]);
// console.log(1,attr);
// xhr[attr] = function () {
// methods[attr](that) || f.apply(xhr, arguments);
// }
} else {
xhr[attr] = f;
}
};
};
return this.hookReplace(_global, 'XMLHttpRequest', function (XMLHttpRequest) {
var resFunc = function () {
this.xhr = new XMLHttpRequest();
for (var propertyName in this.xhr) {
var property = this.xhr[propertyName];
if (utils.isFunction(property)) {
// Hook the original method
this[propertyName] = hookMethod.bind(this)(propertyName);
} else {
Object.defineProperty(this, propertyName, {
get: getProperty(propertyName),
set: setProperty(propertyName)
});
}
}
// Allow outer xhr to be accessed internally
this.xhr.xhr = this;
};
_this.hookedToProperties(XMLHttpRequest, resFunc, true);
_this.hookedToString(XMLHttpRequest, resFunc);
return resFunc
});
},
/**
* Hook global XMLHttpRequest (AJAX)
* @param methods {object} Hook callbacks
* @return {*|number} Hook id
*/
hookAjaxV2: function (methods) {
this.hookClass(window, 'XMLHttpRequest', function () {
});
utils.ergodicObject(this, methods, function (method) {
});
},
/**
* Unhook
* @inner
* @memberOf EHook
* @param context Context
* @param methodName Method name
* @param isDeeply {boolean=} Deep unhook [default:false]
* @param eqId {number=} Unhook only the specified id [optional]
*/
unHook: function (context, methodName, isDeeply, eqId) {
if (!context[methodName] || !utils.isFunction(context[methodName])) {
return;
}
var methodTask = this._getHookedMethodTask(context, methodName);
if (eqId) {
if (this.unHookById(eqId)) {
return;
}
}
if (!methodTask.original) {
delete this._getHookedMethodMap(context)[methodName];
return;
}
context[methodName] = methodTask.original;
if (isDeeply) {
delete this._getHookedMethodMap(context)[methodName];
}
},
/**
* Unhook by id
* @inner
* @memberOf EHook
* @param eqId
* @returns {boolean}
*/
unHookById: function (eqId) {
var hasEq = false;
if (eqId) {
var hookedMap = this._getHookedMap();
utils.ergodicObject(this, hookedMap, function (contextMap) {
utils.ergodicObject(this, contextMap, function (methodTask) {
methodTask.task.before = methodTask.task.before.filter(function (before) {
hasEq = hasEq || before.id === eqId;
return before.id !== eqId;
});
methodTask.task.after = methodTask.task.after.filter(function (after) {
hasEq = hasEq || after.id === eqId;
return after.id !== eqId;
});
if (methodTask.task.current && methodTask.task.current.id === eqId) {
methodTask.task.current = undefined;
hasEq = true;
}
if (methodTask.replace && methodTask.replace.id === eqId) {
methodTask.replace = undefined;
hasEq = true;
}
})
});
}
return hasEq;
},
/**
* Remove all hook-related settings
* @inner
* @memberOf EHook
* @param context Context
* @param methodName Method name
*/
removeHookMethod: function (context, methodName) {
if (!context[methodName] || !utils.isFunction(context[methodName])) {
return;
}
this._getHookedMethodMap(context)[methodName] = {
original: undefined,
replace: undefined,
task: {
before: [],
current: undefined,
after: []
}
};
},
/**
* Check whether a method has been hooked
* @inner
* @memberOf EHook
* @param context
* @param methodName
*/
isHooked: function (context, methodName) {
var hookMap = this._getHookedMethodMap(context);
return hookMap[methodName] !== undefined ? (hookMap[methodName].original !== undefined) : false;
},
/**
* Protect an object's property from being tampered with
* @inner
* @memberOf EHook
* @param parent
* @param methodName
*/
protect: function (parent, methodName) {
Object.defineProperty(parent, methodName, {
configurable: false,
writable: false
});
},
preventError: function (parent, methodName, returnValue, context) {
this.hookCurrent(parent, methodName, function (m, args) {
var value = returnValue;
try {
value = m.apply(this, args);
} catch (e) {
console.log('Error Prevented from method ' + methodName, e);
}
return value;
}, context)
},
/**
* Load plugins
* @inner
* @memberOf EHook
* @param option
*/
plugins: function (option) {
if (utils.isFunction(option.mount)) {
var result = option.mount.call(this, utils);
if (typeof option.name === 'string') {
_global[option.name] = result;
}
}
}
};
if (_global.eHook && (_global.eHook instanceof EHook)) {
return;
}
var eHook = new EHook();
/**
* @namespace AHook
* @author Cangshi
* @constructor
* @see {@link https://palerock.cn/projects/006HDUuOhBj}
* @license Apache License 2.0
*/
var AHook = function () {
this.isHooked = false;
var autoId = 1;
this._urlDispatcherList = [];
this._getAutoId = function () {
return autoId++;
};
};
AHook.prototype = {
/**
* 执行配置列表中的指定方法组
* @param xhr
* @param methodName
* @param args
* @private
*/
_invokeAimMethods: function (xhr, methodName, args) {
var configs = utils.parseArrayByProperty(xhr.patcherList, 'config');
var methods = [];
utils.ergodicArrayObject(xhr, configs, function (config) {
if (utils.isFunction(config[methodName])) {
methods.push(config[methodName]);
}
});
return utils.invokeMethods(xhr, methods, args);
},
/**
* 根据url获取配置列表
* @param url
* @return {Array}
* @private
*/
_urlPatcher: function (url) {
var patcherList = [];
utils.ergodicArrayObject(this, this._urlDispatcherList, function (patcherMap, i) {
if (utils.UrlUtils.urlMatching(url, patcherMap.patcher)) {
patcherList.push(patcherMap);
}
});
return patcherList;
},
/**
* 根据xhr对象分发回调请求
* @param xhr
* @param fullUrl
* @private
*/
_xhrDispatcher: function (xhr, fullUrl) {
var url = utils.UrlUtils.getUrlWithoutParam(fullUrl);
xhr.patcherList = this._urlPatcher(url);
},
/**
* 转换响应事件
* @param e
* @param xhr
* @private
*/
_parseEvent: function (e, xhr) {
try {
Object.defineProperties(e, {
target: {
get: function () {
return xhr;
}
},
srcElement: {
get: function () {
return xhr;
}
}
});
} catch (error) {
console.warn('Failed to redefine the return event; response hook may fail');
}
return e;
},
/**
* 解析open方法的参数
* @param args
* @private
*/
_parseOpenArgs: function (args) {
return {
method: args[0],
fullUrl: args[1],
url: utils.UrlUtils.getUrlWithoutParam(args[1]),
params: utils.UrlUtils.getParamFromUrl(args[1]),
async: args[2]
};
},
/**
* 劫持ajax 请求参数
* @param argsObject
* @param argsArray
* @private
*/
_rebuildOpenArgs: function (argsObject, argsArray) {
argsArray[0] = argsObject.method;
argsArray[1] = utils.UrlUtils.margeUrlAndParams(argsObject.url, argsObject.params);
argsArray[2] = argsObject.async;
},
/**
* 获取劫持方法的参数 [原方法,原方法参数,原方法返回值],剔除原方法参数
* @param args
* @return {*|Array.<T>}
* @private
*/
_getHookedArgs: function (args) {
// 将参数中'原方法'剔除
return Array.prototype.slice.call(args, 0).splice(1);
},
/**
* 响应被触发时调用的方法
* @param outerXhr
* @param funcArgs
* @private
*/
_onResponse: function (outerXhr, funcArgs) {
// 因为参数是被劫持的参数为[method(原方法),args(参数)],该方法直接获取参数并转换为数组
var args = this._getHookedArgs(funcArgs);
args[0][0] = this._parseEvent(args[0][0], outerXhr.xhr); // 强制事件指向外部xhr
// 执行所有的名为hookResponse的方法组
var results = this._invokeAimMethods(outerXhr, 'hookResponse', args);
// 遍历结果数组并获取最后返回的有效的值作为响应值
var resultIndex = -1;
utils.ergodicArrayObject(outerXhr, results, function (res, i) {
if (res != null) {
resultIndex = i;
}
});
if (resultIndex !== -1) {
outerXhr.xhr.responseText_ = outerXhr.xhr.response_ = results[resultIndex];
}
},
/**
* 手动开始劫持
* @inner
* @memberOf AHook
*/
startHook: function () {
var _this = this;
var normalMethods = {
// 方法中的this指向内部xhr
// 拦截响应
onreadystatechange: function () {
if (this.readyState == 4 && this.status == 200 || this.status == 304) {
_this._onResponse(this, arguments);
}
},
onload: function () {
_this._onResponse(this, arguments);
},
// 拦截请求
open: function () {
var args = _this._getHookedArgs(arguments);
var fullUrl = args[0][1];
_this._xhrDispatcher(this, fullUrl);
var argsObject = _this._parseOpenArgs(args[0]);
this.openArgs = argsObject;
_this._invokeAimMethods(this, 'hookRequest', [argsObject]);
_this._rebuildOpenArgs(argsObject, args[0]);
},
send: function () {
var args = _this._getHookedArgs(arguments);
this.sendArgs = args;
_this._invokeAimMethods(this, 'hookSend', args);
}
};
// 设置总的hookId
this.___hookedId = _global.eHook.hookAjax(normalMethods);
this.isHooked = true;
},
/**
* 注册ajaxUrl拦截
* @inner
* @memberOf AHook
* @param urlPatcher
* @param configOrRequest
* @param response
* @return {number}
*/
register: function (urlPatcher, configOrRequest, response) {
if (!urlPatcher) {
return -1;
}
if (!utils.isExistObject(configOrRequest) && !utils.isFunction(response)) {
return -1;
}
var config = {};
if (utils.isFunction(configOrRequest)) {
config.hookRequest = configOrRequest;
}
if (utils.isFunction(response)) {
config.hookResponse = response;
}
if (utils.isExistObject(configOrRequest)) {
config = configOrRequest;
}
var id = this._getAutoId();
this._urlDispatcherList.push({
// 指定id便于后续取消
id: id,
patcher: urlPatcher,
config: config
});
// 当注册一个register时,自动开始运行劫持
if (!this.isHooked) {
this.startHook();
}
return id;
}
// todo 注销 cancellation: function (registerId){};
};
_global['eHook'] = eHook;
_global['aHook'] = new AHook();
return [{
name: 'eHook',
module: eHook
}, {
name: 'aHook',
module: _global['aHook']
}]
}));
/***/ }),
/* 1 */
/***/ (function(module) {
(function (global, factory) {
"use strict";
if ( true && typeof module.exports === "object") {
module.exports = factory(global, true);
} else {
factory(global);
}
}(typeof window !== "undefined" ? window : this, function (_global, noGlobal) {
var map = Array.prototype.map;
var forEach = Array.prototype.forEach;
var reduce = Array.prototype.reduce;
var BaseUtils = {
/**
* 对象是否为数组
* @param arr
*/
isArray: function (arr) {
return Array.isArray(arr) || Object.prototype.toString.call(arr) === "[object Array]";
},
/**
* 判断是否为方法
* @param func
* @return {boolean}
*/
isFunction: function (func) {
if (!func) {
return false;
}
return typeof func === 'function';
},
/**
* 判断是否是一个有效的对象
* @param obj
* @return {*|boolean}
*/
isExistObject: function (obj) {
return obj && (typeof obj === 'object');
},
isString: function (str) {
if (str === null) {
return false;
}
return typeof str === 'string';
},
uniqueNum: 1000,
/**
* 根据当前时间戳生产一个随机id
* @returns {string}
*/
buildUniqueId: function () {
var prefix = new Date().getTime().toString();
var suffix = this.uniqueNum.toString();
this.uniqueNum++;
return prefix + suffix;
}
};
//
var serviceProvider = {
_parseDepends: function (depends) {
var dependsArr = [];
if (!BaseUtils.isArray(depends)) {
return;
}
forEach.call(depends, function (depend) {
if (BaseUtils.isString(depend)) {
dependsArr.push(serviceProvider[depend.toLowerCase()]);
}
});
return dependsArr;
}
};
var factory = function (name, depends, construction) {
if (!BaseUtils.isFunction(construction)) {
return;
}
serviceProvider[name.toLowerCase()] = construction.apply(this, serviceProvider._parseDepends(depends));
};
var depend = function (depends, construction) {
if (!BaseUtils.isFunction(construction)) {
return;
}
construction.apply(this, serviceProvider._parseDepends(depends));
};