What Is Self-Defending JavaScript?
Self-defending mode is an obfuscation feature that causes your JavaScript to break or stop working if someone attempts to modify, format, or tamper with it. It's one of the most aggressive protection mechanisms available — effectively making your code actively resist analysis.
How Self-Defending Mode Works
When self-defending mode is enabled, the obfuscator injects code that continuously monitors its own source representation. Specifically, it uses a technique based on function toString() — it converts functions to strings and checks their content against expected values.
Here's the core mechanism:
// Simplified illustration of the self-defending mechanism
(function() {
var check = function(src) {
var expected = 'function check';
return src.toString().indexOf(expected) !== -1;
};
setInterval(function() {
if (!check(check)) {
// Code has been modified — stop execution
while (true) {} // Infinite loop
}
}, 4000);
}());
The real implementation is far more complex and itself obfuscated, but the principle is: the code knows what it should look like, and if it doesn't match, it freezes or throws errors.
What It Defends Against
Self-defending mode specifically targets:
- Code formatters/beautifiers — Tools that reformat obfuscated code to make it readable will break the self-defense checks
- Manual line breaks — Adding newlines or spaces to "read" the code triggers the defense
- Simple regex substitutions — Trying to rename variables or decode strings manually will modify function toString() output
- Some automated deobfuscators — Tools that rewrite the AST often change whitespace or formatting in ways the self-defense detects
Limitations to Know
Self-defending mode is not a perfect shield. Sophisticated reverse engineers who understand how it works can patch out the self-defense checks before proceeding with analysis. AST-level transformations that preserve toString() output can also bypass it.
Its main value is against casual reverse engineers and automated tools, not against determined expert adversaries.
Important Caveats
Self-defending mode works by triggering an infinite loop or error when tampering is detected. This means if something in your deployment environment inadvertently modifies the code (a CDN that minifies, a proxy that reformats, or a template engine that processes the JS), your code will break in production.
Always test self-defending code in the exact environment where it will be served. Serve it as a static file, not through any transformation layer.
Combining With Debug Protection
Self-defending mode pairs naturally with debug protection. While self-defending mode prevents static analysis by breaking formatted code, debug protection prevents dynamic analysis by blocking DevTools. Together, they create a two-layer defense against both static and runtime analysis.