I want to inject code in javascript, for debugging purposes, within every one of my method prototypes in javascript. This example shows one class only, but assume I have hundreds of classes and each class has dozens of methods. This mechanism should perform at prototype level without the need to specify each class/method name.
function MyClass1() {
this.attrib = "ABC";
}
MyClass1.prototype.myMethod = function() {
alert("first row"); // <---- THE INJECTION SHOULD OCCUR BEFORE THIS LINE OF CODE
}
The idea is to dynamically inject some code before the first row of myMethod(), during the first loading/execution of the javascript code. Such as:
MyClass1.prototype.myMethod = function() {
alert("I was injected dynamically");
alert("first row");
}
So for every other Class and Method, the same should happen. Is this achievable using the Function.prototype approach ?
JavaScript injection is a process by which we can insert and use our own JavaScript code in a page, either by entering the code into the address bar, or by finding an XSS vulnerability in a website. Note that the changes can only be seen by you and are not permanent.
__proto__ Deprecated: This feature is no longer recommended.
Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
We can access the function's prototype property using functionName. prototype . As seen from the above image prototype property of the function is an object (prototype object) with two properties: constructor property which points to Human function itself.
Just wrap your method. Here is the standard method:
MyClass1.prototype.myMethod = function() {
alert("first row");
}
Then wrap it:
var orig = MyClass1.prototype.myMethod;
MyClass1.prototype.myMethod = function() {
alert('Injected');
return orig.apply(this, arguments);
}
You are asking two questions, and I've only answered one of them (i.e. how to wrap a function). The other part - how to do this on many functions - is best done using a specialized library. In fact, this can be done using Aspect Oriented Programming (AOP). I found a couple of JavaScript libraries that offers this, one of them is Aop.js (try googling for more yourself).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With