Search code examples
javascripthtmlunithtmlunit-driver

How to measure the number of JavaScript functions that define new Strings


I was looking through this paper, in which they use HTMLUnit to "measure the number of invocations of JavaScript functions that can be used to define new strings (such as substring, and fromCharCode), and the number of string uses (such as write operations and eval calls)."

I am new to HTMLUnit, and I can't seem to figure out how one can directly see the functions that a website is using and count which ones are substring, eval etc.? How exactly can this be done?


Solution

  • The easiest approach is to monkeypatch all the native calls. For example:

    const original = String.fromCharCode;
    String.fromCharCode = function(...args) {
      console.log('creating new string');
      return original.apply(this, args);
    }
    console.log(String.fromCharCode(65, 66, 67));

    This allows you to keep the original functionality while still allowing you to keep track of what's going on. While more complex, the same can be applied (no pun intended) to eval and any other native call.
    If you also want to monitor any DOM changes, you can use MutationObservers.