【问题标题】:How to watch variables according to their content instead of their name?如何根据变量的内容而不是名称来观察变量?
【发布时间】:2016-05-20 00:43:13
【问题描述】:

我需要用其他值替换所有包含特定字符串或整数值的变量。例如,将所有包含gnl.fr的变量的值替换为nlg.com
在 windbg (windbg 被附加到网络浏览器进程) 中,可以这样实现:

.foreach (hit {s -[1]a 0 L?80000000 "gnl.fr"}) {ea ${hit} "nlg.com"}

但是,它有时会删除关键值,导致网络浏览器崩溃。
绝对可以在 JavaScript 级别执行此操作,而不是处理 Web 浏览器二进制文件。

我不想只为全局变量这样做,但在任何地方都可能这样做(我的意思是包括来自其他 JavaScript 函数的局部变量,而不是当前正在调试的函数)

问题是我什至不知道如何在当前范围之外的变量中进行搜索。

投票结束前,不清楚的请注意所有标签!

【问题讨论】:

  • 唯一可以动态访问的变量是全局变量,因为它们是window 的属性。没有办法获取所有的局部变量。
  • 不需要关闭这个。这是一个完全可以接受的问题。它只是需要一些注意。
  • 这听起来像是一个 XY 问题。你真的想用这个来完成什么?
  • 如果您希望对 www.gnl.fr 的所有访问都转到 www.nlg.com,您可以使用 www.nlg 在 www.gnl.fr 的 /etc/hosts 文件中添加一个条目.com 的地址。
  • 你为什么不直接拦截XMLHttpRequest.send()并在数据中搜索你想要替换的字符串?

标签: javascript global-variables local-variables javascript-debugger


【解决方案1】:

递归地遍历每个对象及其子对象。修改特定的孩子。 为了防止与递归相关的错误,您可以指定要进入孩子的孩子的级别。


下面例子的cmets中进一步解释:

/**
Replace all strings from @inObj matching @toReplace with @replaceWith
*/

var replace = function(inObj, toReplace, replaceWith, optionalArguments){



  console.log("before", inObj);

  var recursion = function(obj, recursionLevel){

    if(typeof recursionLevel === 'undefined'){
      recursionLevel = 0;
    }

    recursionLevel++;

    if(typeof optionalArguments !== 'undefined'){
      if( typeof optionalArguments.maxRecursionLevel !== 'undefined' && recursionLevel > optionalArguments.maxRecursionLevel ){ // simply return the object if maxRecursionLevel reached
        return obj;
      }
    }

    for(var b in obj) { 
      if(typeof obj.hasOwnProperty !== 'undefined' && obj.hasOwnProperty(b)){
        if(typeof obj[b] === "string"){ // element is a string - here we do the actual work: replacing the strings
          obj[b] = obj[b].replace(toReplace, replaceWith);
        }else if(typeof obj[b] === "object" && obj[b]){ // element is an object - call as an object "recursively"
          obj[b] = recursion(obj[b], recursionLevel);
        }
      }
    }
    return obj;
  }

  inObj = recursion(inObj);
  console.log("after", inObj);
  return inObj;
}


/**
example for a test object
*/
var testObj = {
  a: "abc",
  b: "xyz",
  c: {
    aa: {
      aaa: "abc",
      bbb: "abc"
    },
    bb: "abc"
  },
  d: {
    aa: "abc"
  }
};

replace(testObj, /bc/i, "X", {maxRecursionLevel:2}); // for two levels
//replace(testObj, /bc/i, "X");  // for all levels



/**
example for the global scope
*/
//replace(window, /gnl.fr/i, "nlg.com");

【讨论】:

  • 我认识到搜索全局变量可能是第一步。就我而言,该值位于 Json 文件中的已解析数组中。那么虽然它可以是一个全局的,但是如何遍历窗口的子对象呢?
  • 我更新了我的答案,包括处理儿童的递归方法。
  • 谢谢,如何处理 TooMuchRecursion 异常? (如果浏览器发送错误,因为递归太深,我的意思是跳过对象)。我也想没有递归函数(调用堆栈在chrome上限制为小于1000)
  • 问题是这些错误不能用 try/catch 捕获。
  • 现在我添加了对最大递归级别的支持
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多