-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathhook.js
93 lines (86 loc) · 2.62 KB
/
hook.js
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
/**
Code by pnig0s[Knownsec&FreeBuf]
Date 20130214
一個通用的js任意函數鉤子
A simple hooks to Javascript functions
[bool]hook:params{
realFunc[String|must]:用於保存原始的目標函數名,用於unHook;
hookFunc[Function|must]:替換的hook函數;
context[Object|opt]:目標函數實例的對象,用於hook非window對象下的函數,如String.protype.slice,carInstance1
methodName[String|opt]:用於hook匿名函數eg:this.Begin = function(){....};
}
[bool]unhook:params{
realFunc[String|must]:用於保存原始的目標函數名,用於unHook;
funcName[String|must]:被Hook的函數名稱
context[Object|opt]:目標函數實例的對象,用於hook非window對象下的函數,如String.protype.slice,carInstance1
}
**/
function Hooks()
{
return {
initEnv:function () {
Function.prototype.hook = function (realFunc,hookFunc,context,funcName) {
var _context = null; //函數上下文
var _funcName = null; //函數名
_context = context || window;
_funcName = funcName || getFuncName(this);
_context[realFunc] = this;
if(_context[_funcName].prototype && _context[_funcName].prototype.isHooked)
{
console.log("Already has been hooked,unhook first");
return false;
}
function getFuncName (fn) {
// 獲取函數名稱
var strFunc = fn.toString();
var _regex = /function\s+(\w+)\s*\(/;
var patten = strFunc.match(_regex);
if (patten) {
return patten[1];
};
return '';
}
try
{
eval('_context[_funcName] = function '+_funcName+'(){\n'+
'var args = Array.prototype.slice.call(arguments,0);\n'+
'var obj = this;\n'+
'hookFunc.apply(obj,args)\n'+
'return _context[realFunc].apply(obj,args);\n'+
'};');
_context[_funcName].prototype.isHooked = true;
return true;
}catch (e)
{
console.log("Hook failed,check the params.");
return false;
}
}
Function.prototype.unhook = function (realFunc,funcName,context) {
var _context = null;
var _funcName = null;
_context = context || window;
_funcName = funcName;
if (!_context[_funcName].prototype.isHooked)
{
console.log("No function is hooked on");
return false;
}
_context[_funcName] = _context[realFunc];
delete _context[realFunc];
return true;
}
},
cleanEnv:function () {
if(Function.prototype.hasOwnProperty("hook"))
{
delete Function.prototype.hook;
}
if(Function.prototype.hasOwnProperty("unhook"))
{
delete Function.prototype.unhook;
}
return true;
}
};
}