Merolla
Merolla

Reputation: 315

Grabbing JavaScript variables as they change using Selenium

I know I can grab the value of a JavaScript variable using Selenium Java APIs as follows

JavascriptExecutor je = (JavascriptExecutor) driver;
Long JSvar = (Long)je.executeScript("return variable");

But is there a way in Selenium to get every value for that variable as it changes in JS code. For example if my JS code looks as follows

var variable=1;
/* some code */
variable=2;
/* some code */
variable=3;

Is there a way to grab these three values (1,2,3)? Something like putting a breakpoint on the JS code but in an automated way. I was thinking that I could store these values in an array and then grab the array but is there another way in Selenium to handle this with the minimal changes to the JS code?

Upvotes: 0

Views: 459

Answers (1)

Greg Burghardt
Greg Burghardt

Reputation: 18783

You have not specified how or when Selenium should retrieve these values, but here is some JavaScript code that at least makes these values available:

(function(window) {
    var values = [];
    var someVariable;

    Object.defineProperty(window, 'someVariable', {
        get: function() {
            return someVariable;
        },

        set: function(value) {
            someVariable = value;
            values.push(value);
        }
    });

    Object.defineProperty(window, 'someVariableValues', {
        get: function() {
            return values;
        }
    });
})(this);

Whether JavaScript code executes window.someVariable = X or simply someVariable = X, the setter will push that value onto the array. Selenium (or JavaScript for that matter) can access window.someVariableValues to return the historical and current values of that variable.

Retrieving this using Selenium could be:

JavascriptExecutor je = (JavascriptExecutor) driver;

// Get current value of variable
Long JSvar = (Long)je.executeScript("return someVariable");

// Get all values assigned to variable (this part I'm not 100% sure about)
Long[] historicalValues = (Long[])je.executeScript("return someVariableValues");

Upvotes: 1

Related Questions