Sending data from JavaScript to Java with a keypress

Is it possible to utilize Selenium to open a URL and execute a script? If so, how can I pass a value back to my Java program when the 'Escape' key is pressed?

This particular functionality in my code involves the following Java program:

JavascriptExecutor js = (JavascriptExecutor) driver;
String content = new String(Files.readAllBytes(Paths.get("xp_simple.js")));
String str = (String) js.executeScript(content);
System.out.println("Returned from js : " + str);

The associated javascript string that gets passed is as follows:

var pageName='value from webpage';
window.addEventListener('keydown', function (zEvent) {
    if (zEvent.key === 'Escape') {
    console.log("Escape is pressed");
    return getSG()
     }
} );
function getSG() {
        return pageName;
};

An ongoing issue manifests as control not remaining until the Escape key is pressed. Instead, the program immediately reverts back to Java with the value of 'str' being null.

Answer №1

The code snippet below successfully executed.

String fileContent = new String(Files.readAllBytes(Paths.get("xpo_simple.js")));
String strResult = (String) js.executeAsyncScript(content);

Here is the JavaScript portion of the code:

var pageName='value from webpage';
var callback=arguments[arguments.length - 1];

window.addEventListener('keydown', function (zEvent) {
    if (zEvent.key === 'Escape') {
    console.log("Escape is pressed");
        callback(getSG());
     }
} );
function getSG() {
        return pageName;
};

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

Oops! The function 'ModalDemoCtrl' has not been defined, causing an error

Hey there, I'm encountering an error when using angularJS in my project. The project is built on the django framework and does not include any additional JS files. Here are some snippets of my code: JavaScript: {{ ngapp }}.controller("ModalDemoCtrl" ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

Loading HTML and jQuery dynamically using AJAX

I am struggling to access a child element of HTML that is loaded dynamically through AJAX. Unfortunately, it's not working as expected. $.get('test.html', function(data) { var content = $('#content', data).html(); conso ...

Is it necessary to define module.exports when using require() to import a file?

While setting up my Express server, I am using Babel to transpile my ES6 files seamlessly. In my vanilla JS server.js file, I include require('babel-core/register') and require('./app'). Within my ES6 file app.js, I handle all the usua ...

I encountered an error while using the router: TypeError: Cannot read property 'use' of undefined

Hello everyone, I am new to node.js and seeking help from experts. I am currently working on a code for user synchronization using node.js + AWS Cognito + Facebook Login. I followed an example from this link. Everything was going smoothly until I reached ...

Adjusting the focus of an element with jQuery based on coordinates and offset values

jQuery.fn.getCoord = function(){ var elem = $(this); var x = elem.offset().left; var y = elem.offset().top; console.log('x: ' + x + ' y: ' + y); ); return { x, y }; }; This custom jQuery funct ...

What is the snapping feature of the jQuery Mobile slider?

I've been diving into various sources for the past couple of hours, attempting to implement code snippets claiming to enable snapping functionality on a slider component. I'm facing doubts about the feasibility of achieving this with the jQuery M ...

The Science behind Selenium Wait Strategies

I am currently developing a testing framework for my website with the aim of completely separating it from the actual tests. However, I have encountered an issue where the Assert sometimes needs to wait before returning true results. For example, when uplo ...

Utilizing Node.js and Mongoose, effortlessly update data in Mongo DB regardless of the existence of the collection

How can I update a field that may or may not exist? I attempted the following code: db.foo.update( { site: '"wisdom'}, { $set: {'club': 'fc barcelona'}}, (upsert=true) ) ...

Modifications made to the process module in one file are not reflected in a different file

It seems that the process module in NodeJS is not global, resulting in changes made to it in one module not reflecting in other modules. To confirm my findings, I wrote a small piece of code. Here is the snippet: server.js import app from "./app.js& ...

Tips for deactivating the highlight on a previously selected menu item when clicking on the next menu option in Angular.js

In my pages, I have a menu where the landing page menu is initially highlighted. However, when I move to the next menu, the previous landing page highlight remains instead of being removed while swapping the menu. I am using Angular.js and angular ui-route ...

Strategies for managing the result of findElements?

Snippet A resultsBoard.findElements(By.css(mySelector)).then(function(elements) { elements.forEach(function(val, idx) { elements[idx].getText().then(function(text) { console.log(text); }); }); }); Snippet B resultsBoard.findElements( ...

The surprising twist of hasOwnProperty's behavior

I am currently working on a function that is designed to check whether an object contains keys such as 'id' or 'serif:id'. However, I have encountered some issues with its functionality. function returnIdPreferSerifId(object) { if ...

Securing ASP.NET Web API with Cross-Domain AJAX Requests: A Comprehensive Guide

I am in the process of developing an API on www.MyDomain.com that needs to be accessible from public websites such as www.Customer1.com and www.Customer2.com. These websites are designed to showcase each customer's inventory without requiring users to ...

What is the duration of time a user has spent on a specific asp.net page according to custom analytics?

I have been brainstorming ways to track how long a user stays on a page within my ASP.NET application. In order to do this, I am saving the userid, pagename, pageenteredtime, and pagelefttime in a database. Each entry also has its own unique identifier kno ...

Using Cx framework: Tips for accessing a DOM element in Cx

Currently, I am delving into the world of Cx, a fascinating new framework built on top of React (). I find myself stuck as I try to access a DOM element within a component. Basically, I have a basic widget that comprises some text and a button. Upon click ...

Ways to access PromiseValue in XMLHttpRequest with JSON

Is there a way to access an array that is within the PromiseValue instead of receiving Promise {<pending>} When I use .then(data => console.log(data)), I can see the array in the console log. However, my requirement is to display this array on an ...

Place an element that exceeds 100% in size at the center

How can I center an image that is larger than its parent element? I have set the min-width and min-height to 100% so that the picture will always fill up the parent element. The issue arises when the image does not match the proportions of the parent elem ...

Exploring AngularJS through interactive sessions

I am working on implementing a basic login system using express and angularjs. The angular js application is running on a different server (grunt server localhost:9000), while the express app is running on a separate port. In my express app, I have configu ...

Application built using the MEAN stack and Java technologies

Having worked as a Java/J2EE developer for several years, I have found that my learning has stagnated due to the nature of my daily job and company. To address this issue, I have decided to embark on my own personal project with the following key details/ ...