禁用特定Javascript文件的控制台访问

Koe*_*nvE 9 javascript

在我当前具有大量依赖项的项目中,我需要一种方法来禁用特定库的控制台访问,以便这些文件不能使用任何控制台功能.

我当然可以通过简单地在库包中找到并替换它来禁用控制台功能,但是因为这个项目有很多依赖性,这会使更新库变得非常麻烦.

我知道我可以通过用空功能块覆盖它来禁用控制台功能:

console.log = function(){};
Run Code Online (Sandbox Code Playgroud)

但是这会禁用整个项目的控制台功能.所以我正在寻找一个实现,或一行代码,我可以用它来禁用特定文件或代码块的控制台功能.

mol*_*amk 2

编写一个白名单“中间件”console.log

// Preserve the old console.log
const log = console.log;

// Used a dictionary because it's faster than lists for lookups
const whiteListedFunctions = {"hello": true};

// Whitelisting "middleware". We used the function's name "funcName"
// as a criteria, but it's adaptable
const isWhitelisted = callerData => callerData.funcName in whiteListedFunctions;

// Replacing the default "console.log"
console.log = arg => {
  const stack = new Error().stack.split("at")[2].trim().split(' ');
  const fileParts = stack[1].substr(1, stack[1].length - 2).split(':');

  const callerData = {
    funcName: stack[0],
    file: fileParts.slice(0, fileParts.length - 2).join(':'),
    lineColNumber: fileParts.slice(fileParts.length - 2).join(':')
  };
  
  if (isWhitelisted(callerData)) {      // Filtering happens here
    log(arg);
  }
};

// Define the calling functions
function hello() { console.log("hello"); }
function world() { console.log("world"); }

hello(); // => Prints hello
world(); // => Doesn't print anything
Run Code Online (Sandbox Code Playgroud)

方法说明

  • 您可以通过创建包含您的过滤条件的白名单 (或黑名单)来做到这一点。例如,它可能包含调用的函数的名称,或者可能是文件名,甚至是行号和列号console.log
  • 之后,您创建白名单“中间件”。这将获取调用者函数数据并决定它是否可以记录内容。这将根据先前定义的白名单来完成。您可以在此“中间件”中选择您的首选标准。
  • 然后你实际上console.log通过用新的 logger覆盖来替换。该记录器将把要记录的消息作为参数(可能是多个参数?)。在此函数中,您还需要查找与调用者函数(想要调用)相关的数据console.log
  • 一旦获得调用者数据,您就可以使用白名单中间件来决定它是否可以记录内容。

获取有关调用者函数的信息

这部分有点“hacky”(但在本例中它完成了工作)。我们基本上创建一个Error并检查它的stack属性,如下所示new Error().stack。这会给我们这个痕迹

console.log.arg [as log] ( https://stacksnippets.net/js:25:7 )的错误在 hello ( https://stacksnippets.net/js:41:11 ) 在https://stacksnippets 。净/js:48:1

处理(分割、映射等)跟踪后,我们得到调用函数数据。例如这里我们有

  • 调用函数的名称:hello
  • 文件名: https: //stacksnippets.net/js
  • 行数和列数:41:11(注意缩小器)

这一点的灵感来自于VLAZ如何根据特定 javascript 源(方法、文件)或消息内容的条件禁用 console.log 消息中的答案,因此请务必检查一下。非常好的和彻底的帖子。

笔记

为了理解跟踪,我们可以知道new Error().stack.split("at")[INDEX].trim().split(' ')您想要在堆栈跟踪中定位的函数调用INDEX的位置。因此,如果您想获得与本示例中使用的不同的“级别” ,请尝试更改INDEX