Search code examples
javascriptjavahtmlunit

How to write Event Handlers and detect certain JavaScript calls using HTMLUnit?


I want to use the Java API, HTMLUnit, to detect the number of eval() calls being called on the webpage by the JavaScript program. However, HTMLUnit doesn't have a built in handler for this type of JavaScript function. How can this be done?

Thanks.


Solution

  • Just an idea. Maybe you can inject a script with this code into the start of the html that you are loading:

    (function(){
        const oldEval = window.eval;
        window.eval = function () {
    
            // communicate here with your Java program that eval has been
            // called. Maybe you can use the postMessage method?
    
            return oldEval.apply(this, arguments);
        };
    })();
    

    With this, you hijack the eval function and you can execute some code each time eval is called. If you figure out a good way to communicate back with your program then maybe this works.

    Not sure if an issue or not, but Javascript has multiple ways to evaluate code during runtime, not just eval. So, this is hijacking a direct call to eval, but not considering other evaluation possibilities like using the Function constructor or setTimeout.