An issue is encountered with the JavascriptExecutor while attempting to navigate to a different page using Selenium Webdriver

My goal is to capture user actions such as clicks, keypress, and other DOM events by adding JavaScript event listeners to the WebDriver instance. Everything works fine until I navigate to the next page, where I encounter an exception due to an undefined function caused by changes in the DOM. How can I effectively handle this exception?

Is there a method to store all events temporarily and retrieve them after all web page navigations have been completed?

Here's the code snippet:

((JavascriptExecutor) driver)
    .executeScript("(function() {
        var events = [];
        window.addEventListener('click', function(e) {
            events.push([+new Date(), 'click', [e.clientX, e.clientY], e.target.name, e.target.id]);
        }, true);
        window.addEventListener('keypress', function(e) {
            events.push([+new Date(), 'keypress', e.target.name, e.target.id, String.fromCharCode(e.keyCode)]);
        }, true);
        window._getEvents = function() {
            return events;
        };
    })();
");

response = (ArrayList)((JavascriptExecutor) driver)
    .executeScript("return window._getEvents();");

Answer №1

One way to store data locally is by utilizing localStorage

localStorage.setItem('key', JSON.stringify(events)); 

When needed, you can retrieve the data like this:

return JSON.parse(localStorage.getItem('key'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance Your Charts: Learn how to dynamically adjust zoom levels between two timestamps with just a simple form submission

I have a Zingchart Area Graph that displays events on a timeline with time on the X-Axis. I want to be able to automatically zoom into a specific timeframe on the graph based on user input from a form. For example, if a user selects a start time of 8 AM an ...

Angular's ng-include functionality allows developers to dynamically load

As a beginner in angular.js, I've written my first 'hello world' script. I'm attempting to use ng-include to bring in a navbar from the local file /templates/nav.html. Despite following a tutorial closely, I'm struggling to underst ...

Tips for choosing an element based on parameters provided in the button's onclick function

I am looking to target a specific button based on a timestamp. Here is the HTML code: <a class="mdc-button mdc-button--unelevated mdc-ripple-upgraded" href="#" onclick="selectTime(7160, null, &quot;2021-08-23T08:15:00-04:00& ...

What is the best way to modify a variable in a nested element using ng-click in the parent element?

Review this code snippet: <section class="page-section about-us" scroll-bookmark="about-us" ng-click="activeSection=true" ng-init="activeSection=false"> <div class="page-content sub-content active-section">{{activeSection}} < ...

JavaScript Object has Not Been Defined

Currently, I am developing a small program for myself related to a video game. The main issue I am facing is that certain objects are being flagged as not defined when the errors appear on the page. $(document).ready(function(){ //A list of chara ...

What could be the reason why the initial console.log is failing to print?

Apologies for the oversight. The !== was a mistake that slipped past me before posting. Thank you for your understanding. I am a beginner in Javascript. I have written this function with winston: function setlogger(log_level = "warn", logfile, scree ...

My React project is altering the direction of my image

Below is the code snippet used to retrieve the user's favorite products import React, { useEffect, useState } from "react"; import { Pagination, Row } from "react-bootstrap"; import { useDispatch, useSelector } from "react-red ...

Selenium in Python fails to execute the clicking action

My mind is spinning with frustration. I am trying to click on a specific button, but an unknown error keeps popping up: Traceback (most recent call last): File "C:\Users\leosc\PycharmProjects\ogameBot\guideline.py", line 22, i ...

React JS - Building a dynamic multi-tiered dropdown navigation system

Link to view the illustrative example: here. Could anyone advise on a solution for ensuring only one submenu is open at a time? For instance, when "menu 3" is opened, I would like "menu 2" to be automatically closed. ...

What is the best way to position a <td> element within a table row underneath another <td>?

Looking for a solution to ensure Content 3 appears below Content 2 in this block of HTML. Content 1 is extensive and extends far down the page. <table> <tr> <td>(Content 1)</td> <td>(Content 2)</td> ...

Overriding FindsBy attribute in a Selenium subclass

In my use of the Page Object Model pattern, I rely on PageFactory to initiate the properties and fields of the IWebElement. My issue lies in wanting a derived class that overrides the IWebElement with a different [FindsBy] attribute. Here is my base class: ...

How can one element be made to rely on the presence of another element?

I'm currently working on my portfolio website and encountering an issue. Whenever I hover over an image of a project, the image expands in size, becomes less transparent, and a description of the project pops up. However, I would like to include a lin ...

Transforming the format from YYYYMMDD using MomentJS

Currently, I have a date in the format of YY as shown here: 20141229. I am attempting to convert it into Timestamp format. I attempted using moment(date).format('x'), but received an "Invalid date" error. I'm unsure of how to accomplish this ...

Is there a way to use SCTP with Socket.io and Node.js?

I have a new project in the works, creating a web application that will utilize web sockets to provide real-time updates for users. The plan is to seamlessly transmit changes from the back-end engine. My challenge lies in Node.js not supporting SCTP sock ...

Mongoose Alert Utility Directive

const mongoose = require('mongoose'); module.exports = { init: () => { const dbOptions = { useNewUrlParser: true, useUnifiedTopology: true, autoIndex: false, reconnectTries: Number.MA ...

The issue with ui-router failing to render the template in MVC5

I'm having trouble setting up a basic Angular UI-Router configuration. My goal right now is to have a hardcoded template render properly, and then work on loading an external .html file. My project is using MVC5, so I'll provide the necessary fi ...

It is not possible to access fields in Firestore using Node.js

Exploring the limits of my Firestore database access with a test function: exports.testfunction = functions.https.onRequest(async (request, response) => { try{ const docRef = firestore.collection("Stocks").doc("Automobile" ...

The challenge of maintaining coherence in AngularJS scopes

It's driving me crazy. Our integration with some ATSs involves sending queries and setting variables in the scope upon receiving responses. I always make sure to set the variables within a $scope.$apply() to ensure proper updating. Everything was work ...

A comprehensive guide on using Lua Script in Node.js to efficiently insert multiple records into a Redis Hash

How can I efficiently insert multiple records into a Redis Hash using Lua Script in Node.js? I currently have the following code which utilizes multi and exec for inserting data. How can I modify it to use a lua script instead? return new Promise ...

Having trouble getting nodeJS socket.io to function properly on my Raspberry Pi

Being new to nodeJS and programming, I've been trying to get this piece of code to function properly with no success. It's frustrating because I can't figure out why it's not working, and I am clueless on how to troubleshoot it. Despite ...