Best way to detect when a function is called from the console

删除回忆录丶 提交于 2019-12-03 20:41:48
Sukima

To prevent global access make sure your code is in a closure. If you want to expose an API you can do so using the module pattern.

Closure

(function() {
  var Game = {};
  Game.giveMoney = function(money) {
    console.log('Gave money (' + money + ')');
  };
})();

Wrap all your private code in an IIFE (Immediately Invoked Function Expression) which will lock it up into a closure.

Module

Then expose only custom functions back out of the closure so you can use them on the console (with supervision of course).

window.Game = (function() {
  var player = {
    money: 500;
  };
  player.giveMoney = function(money) {
    console.log('Gave money (' + money + ')');
    player.money += money;
  };
  player.takeMoney = function(money) {
    console.log('Took money (' + money + ')');
    player.money -= money;
  };

  return {
    giveMoney: function(money) {
      console.error('Don\'t Cheat! A fine was charged.');
      player.takeMoney(Math.floor(player.money / 0.05));
    }
  };
})();

window.Game.giveMoney(200);

You can spool all function calls through a central access point with a boolean variable, that can serve as a indicator whether the call is from a console or not....

var maths = {
    add: function(p1,p2)
    {
        console.log(p1,p2);
    }
}

var invoker = {
    invoke: function(fu,isconsole)
    {
        if(isconsole)
        {
            console.log("Called from console");
        }

        //invokes the function with all parameters intact
        fu;
    }
}

//Call without console
invoker.invoke(maths.add(2,3));

//Call with console
invoker.invoke(maths.add(2,3),true);

Hope it helps!!!

You can use the monitor() command in the console to monitor when a function is called. https://developer.chrome.com/devtools/docs/commandline-api#monitorfunction

Just run monitor(functionName); and whenever the function is called it will output a message in the console.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!