In this code I created a function called someFunction. Then I modified Function.prototype.apply and call methods. So instead of my function code is working I am running my interception code (which shows an alert). But neither "call" nor "apply" intercepts direct method call. Is it possiple to intercept this?
Function.prototype.call = function(){alert("call");}; Function.prototype.apply = function(){alert("apply");}; function someFunction(){} window.onload = function(){ someFunction.call(this); //call alert is shown someFunction.apply(this); //apply alert is shown someFunction(); //how can I intercept this? }
You can only override a known function by setting another function in its place (e.g., you can't intercept ALL function calls):
(function () { // An anonymous function wrapper helps you keep oldSomeFunction private var oldSomeFunction = someFunction; someFunction = function () { alert("intercepted!"); oldSomeFunction(); } })();
Note that, if someFunction
was already aliased/referenced by another script before it was changed by this code, those references would still point to the original function not be overridden by the replacement function.
Function.prototype.callWithIntercept = function () { alert("intercept"); return this.apply(null, arguments); };
var num = parseInt.callWithIntercept("100px", 10);
It is worth noting that in newer versions of JS, there are Proxy
objects you can use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
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