2

In my Javascript code I have this

function log_function() {

   console.log("WHO FIRED ME");

}

window.alert = log_function;
window.open = log_function;
window.confirm = log_function;

Inside the function log_function I would like to know "who" fired the "log_function". Is it possible? I will assign that function to many more functions, so I would like to know who fired the log_function.

For example, if inside a page there is a script like:

alert("aaa");

I would like to know that it was the "alert" who was blocked and log it in the console.

2 Answers2

1

You could use a closure:

function log_function(caller) {
   return function() {
      console.log(caller + " FIRED ME");
   }
}

window.alert = log_function('alert');
window.open = log_function('open');
window.confirm = log_function('confirm');
Ram
  • 143,282
  • 16
  • 168
  • 197
  • it would not be practical cause I will be blocking many functions (probably around 300) and it would take too much time to do that. Isnt it possible something like arguments.callee? – gessicamilar Sep 15 '15 at 19:56
  • I like it. Clean and concise. – Brad Christie Sep 15 '15 at 19:56
  • 1
    @gessicamilar: you could feed it from an array of names, you don't have to hard-code each blocked var name... `["alert","confirm","whatev"].forEach(function(key){window[key]=log_function(key);})` does the same as the last 3 lines, but you can see how to expand it much more quickly... (or feed it something _like_ `Object.keys(window)`) – dandavis Sep 15 '15 at 20:02
0

Could modify the context and pass along a describing property:

window.alert = function(){
  var _this = this || {};
  _this.caller = 'window.alert';
  log_function.apply(_this, arguments);
};
window.open = function(){
  var _this = this || {};
  _this.caller = 'window.open';
  log_function.apply(_this, arguments);
};
window.confirm = function(){
  var _this = this || {};
  _this.caller = 'window.confirm';
  log_function.apply(_this, arguments);
};

Then you can reference this.caller in your log method.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • Nice but it would still give me a hell of a job to block around 300 functions using 5 block of code for each function to block – gessicamilar Sep 15 '15 at 19:57
  • [`arguments.callee`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee) is acceptable, but from what I'm gathering it will give you trouble in strict mode. Not sure if that's a problem. However, [`arguments.caller`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller) is marked as troublesome. – Brad Christie Sep 15 '15 at 19:58
  • do you have any idea how I could achive tihs using arguments.callee ? I dont care about strict mode, it's an application that I will run under controlled circunstances. – gessicamilar Sep 15 '15 at 20:00
  • Callee is deprecated now that's what I read about the strict mode. – EasyBB Sep 15 '15 at 20:04