DEV Community

Cover image for Why does the action swap in array when clicking after typing in javascript?
DemoDev95
DemoDev95

Posted on

Why does the action swap in array when clicking after typing in javascript?

I've created a chrome extension to capture the elements in the DOM according to the click order. The XPath obtained there is pushed to an array as follows. The function that performs it is as follows.

var actionArray = [];
        function Capture(json) {

            var lastCaptureStep = actionArray[actionArray.length-1];
            if(lastCaptureStep && lastCaptureStep.activity=="CLICK" && lastCaptureStep.timestamp+100>json.timestamp){
                actionArray[actionArray.length-1] = json;
                actionArray.push(lastCaptureStep);
            }else{
                 actionArray.push(json);
            }
        }
Enter fullscreen mode Exit fullscreen mode

The received JSON is as follows.

    {
        "activity": "TYPE",
        "xpath": "//input[@id='password']",
        "value": "Password",
        "frames": [],
        "timestamp": 1658992410657
    }
Enter fullscreen mode Exit fullscreen mode

But in the following scenario, when the password is typed in the login screen and the remember me button is clicked, the two actions are swapped as remember me click first and type action after that. (for more details please see the image).

Swapped Array
What is the reason for this? Is there a problem with the logic in my function?

Top comments (2)

Collapse
 
cwisefool profile image
cwisefool

Have you tried stepping through your code to see what is happening with actionArray at each iteration?

Looking at the code, that if branch for CLICK seems problematic. You're overwriting the last element in the array with the passed JSON, but then pushing what was previously the last element onto the end. So if the order was TYPE, CLICK, then (assuming that the timestamp portion is also true when CLICK)

on TYPE
actionArray[0] = json for TYPE

on CLICK
actionArray[0] = json for CLICK
actionArray[1] = json for TYPE

Collapse
 
demodev profile image
DemoDev95 • Edited

One thing I have seen here is that even if I CLICK remember me checkbox after password TYPE, as in the image above remember me has received a timestamp that was executed before the type action. Therefore, it comes as a first executed step before the TYPE action in the actionArray.