0

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?

3
  • Is the variable a global variable in JavaScript? Commented Apr 14, 2021 at 19:55
  • I think this might be answerable, but there is one thing I am struggling with. Exactly when should Selenium come in to play? Do you want to query for these values at a regular interval, or do you want a real-time update each time the variable is set? Commented Apr 14, 2021 at 20:01
  • I need to capture that variable at specific parts in the code for example at the assignment after the first /* some code*/ block (variable=2) Commented Apr 18, 2021 at 8:14

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.