JavaScript Hook Technical Practical Guide
Front-end analysis, crawler development, and security testing often require "tampering" with web pages during runtime - intercepting function calls, inserting monitoring code, and even modifying execution logic. JavaScript Hook is the core technique to achieve these goals. This article starts from the principle and uses the Tampermonkey script to practice, allowing you to quickly master this technology.
1. What is Hook technology
Hook refers to the technology of replacing or wrapping the original function while the program is running: you can insert your own code before, during, and after the function is executed, while (optionally) retaining all or part of the functionality of the original function.
Its common application scenarios
- Analysis of front-end encryption: intercept the plain text of login token and password before encryption
- Debugging front-end logic: Automatically add breakpoints to function calls that meet specific conditions
- Modify page behavior: block ads and unlock paid content (only for learning and testing)
- Monitor API calls: Track fetch / XHR request and response parameters
2. The most recommended Hook tool on the browser side: Tampermonkey
To do JS Hook in a browser environment, Tampermonkey is the well-deserved first choice:
-Supports Chrome, Edge, Firefox, Safari and other mainstream browsers
- Zero threshold for script installation and management
- Built-in rich GM_* API (cross-domain requests, storage, DOM operations, etc.)
- You can specify the running time and effective domain name of the script
Quick installation
- Chrome/Edge users can directly search for "Tampermonkey Beta" in the app store (the Beta version has more complete functions)
- Firefox users search for "Tampermonkey" in AMO
- Official website backup: https://www.tampermonkey.net/
3. Tampermonkey basic script development
The Grease Monkey script is essentially an ordinary JS code wrapped in a self-executing function, plus a metadata header to tell the browser the basic information about the script.
Complete basic template
High frequency metadata command cheat sheet
4. JS Hook practical basis: three common modes
4.1 Simple function Hook (replacement/wrapping)
This is the most basic Hook method: first save the reference to the original function, then replace the original position with a custom function, call the original function in the custom function and insert the code.
4.2 Prototype chain method Hook
Many front-end API (such as XHR, Canvas) methods are hung in the constructorprototypeOn, the Hook prototype can intercept calls to all instances.
4.3 Conditional Breakpoint Hook
Automatically add debugger breakpoints to function calls that meet specific conditions, so you no longer have to manually find the location and breakpoint!
5. Practical case: analysis of token generation on scrape login page
We use **https://login1.scrape.center/**(崔庆才老师的爬虫练习站)为例,看看怎么用 Hook to find the login token generation logic.
5.1 Early Observation
- Open the website and press F12 to switch to the Network panel
- Enter your username and password (for example
admin/123456) and click Login - find
loginRequest and found that there is only one encrypted one in Form Datatokenfield, no clear text password
5.2 Speculation and Hook
- The encrypted token looks like Base64 encoding
- The common API for doing Base64 on the browser side is
window.btoa() - Direct Hook
btoa, and print the call stack to find the function that called it
5.3 Complete script
5.4 Analysis results
After installing the script, refresh the website and enter the password again to log in:
- The console will print the plaintext before encryption:
{"username":"admin","password":"123456"} - You can find it in the call stack
loginfunction calledbtoa - It turns out that the user name and password are JSON serialized and then directly Base64 encoded.
6. Advanced techniques and anti-Hook confrontation
6.1 Asynchronous function Hook (Promise / async-await)
Today’s front-end APIs (e.g.fetch、axios.get) are mostly asynchronous. When hooking asynchronous functions, you need to pay attention to error capture and return Promise processing.
6.2 Property access Hook (getter/setter)
If you want to monitor whether the properties of an object are assigned or read, you cannot use the function Hook, but useObject.definePropertyOverride getters and setters.
6.3 Simple anti-Hook confrontation
Many websites now provide anti-Hook protection. Common methods include:
- Check whether the API has been modified: For example, compare
btoa.toString()the result - Freeze Object/Property: Use
Object.freeze()、Object.seal()or setwritable: false - Code Obfuscation: Makes it difficult for you to locate Hook points
Simple coping strategies
Note: The above technologies are only for learning and research. Please do not interfere with or attack online services without authorization.
7. Best Practices
- Precise control scope: use
@matchOnly run scripts on required websites - Principle of Least Permission: Only apply for necessary
@grantPermissions, for example, if cross-domain is not required, set it tonone - Do a good job in error handling: Add Hook logic
try-catch, to avoid script crashes affecting the original website - Performance first: Do not use functions that are called frequently (such as
requestAnimationFrame, CanvasdrawMethod) Do too much complex logic - Code reusability: Encapsulate commonly used Hook methods into universal functions
8. Summary
This article takes you from 0 to 1 to master the core skills of browser-side JS Hook:
- What is Hook and its common uses -Basic use and script development of Tampermonkey
- Three commonly used Hook modes (simple function, prototype chain, conditional breakpoint)
- Practical analysis of scrape login page token generation
- Asynchronous functions, attribute access Hooks and simple anti-Hook countermeasures
After mastering these skills, you can start analyzing more complex front-end logic. Please be sure to use it only for learning and testing, not for illegal purposes~

