JavaScript functions can be hooked; hook is a method of dynamically modifying the execution process of a function or returning results. JavaScript, as a dynamic language, can also perform hook operations. Hooks are usually used to listen, print output, etc. for certain parameters or variables. Replacement and other operations.
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
Can.
Hook is a method that dynamically modifies the execution process or return results of a function, and is very widely used in practical applications. As a dynamic language, Javascript can also perform Hook operations. With the development of Javascript language, there are more and more Hook methods.
The literal translation of hook means hook. In the field of reverse engineering, it is usually used to listen, print output, replace and other operations for certain parameters and variables.
Examples are as follows:
Sample code
function add(a,b){return a + b}hook code
This is a very simple addition function. The values of these two parameters can be obtained through Hook, which is equivalent to adding a code console.log(a,b) before return, so that the values of these two can be output for analysis. Then you can use the following method to overwrite the function, and this method is the decorator mode in JavaScript
let _add = addadd = function () { console.log('arguments', arguments) let result = _add.apply(this, arguments) console.log('result', result) return result // If result is not required, then Directly return _add()}Complete code
function add(a, b) { return a + b} let _add = addadd = function () { console.log('arguments', arguments) let result = _add.apply(this, arguments) console.log('result' , result) return result } add(1, 2)Calling add(1,2) again will output the arguments parameters and result 3. A very simple HOOK is implemented.
However, this example may be too simple. What I want to express is that through Hook, we can locate the function and variable we want to Hook, and through a series of operations (function copying, metaprogramming), as long as the function is triggered or used (value, modification ), we can get the results we want (the results before and after (such as before encryption, after encryption)). This is our purpose.
The example given in the book is intended to illustrate that you want to add some functions to a certain original function (such as add here), but the original function may be written by other developers, so directly modifying the original function itself may lead to unknown BUG. , so you can use the above method to copy the original function without destroying the original function.