How can we use the Selenium JavascriptExecutor in Java to return an Object from JavaScript?

I've encountered an issue while running a JavaScript file using Java with Selenium in my application. When I execute the JavaScript file with JavascriptExecutor after logging in, I'm only getting a null return instead of a valid one.

Below is a snippet from my code:

public static void runJavascriptFile(ChromeDriver driver) throws Exception {
        System.out.println("Start");
        Object js = driver.executeScript(TestHelper.getTextFromFile("demo-client/scripts/get-test.js"));
        System.out.println(js);
        System.out.println("End");

    }

The content of my JavaScript file is as follows:

async function getPeople() {
    let response = await fetch("https://swapi.dev/api/people/1/", { method: "GET" })
    console.log("This is from my Javascript File from Java.")
    return response.status;
}
let result = await getPeople();
console.log("result", result);

In the Chrome browser console, I can see the return value from the JavaScript file, but not in my Java IDE: BrowserConsoleXJavaConsole

If anyone has a different approach that could resolve this issue, your help would be greatly appreciated!

Answer №1

To convert it to a string, you can do the following:

JavaScriptExecutor jsExecutor = (JavascriptExecutor) driver;
String contentOfFile = (String) jsExecutor.executeScript("include specific JavaScript code here to retrieve the file's content");
System.out.println(contentOfFile);

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

Python Selenium for Web Scraping

I am currently working on a project to extract data from the Sunshine List website () using the BeautifulSoup library along with the Selenium package. My main challenge is figuring out how and where to instruct the driver to wait for elements to load befor ...

Experiencing a lack of information when trying to retrieve data through an http request in an express/react

Issue: My problem lies in attempting to retrieve data from http://localhost:3000/auth/sendUserData using the http protocol. Unfortunately, I am not receiving any data or response, as indicated by the absence of console logs. Tools at my disposal: The te ...

Comparison of getComputedStyle() and cssText functionality between Internet Explorer and Firefox

Take a look at this example to see the issue in action. I'm attempting to access the cssText property of a <div> using window.getComputedStyle(element) (which provides a CSSStyleDeclaration object). While this works smoothly in Chrome, it' ...

Using repetitive parameters with a paginated datatable and ajax technology

Can someone help me with an issue I'm facing with a datatable/ajax (in short): <h:panelGroup layout="block" styleClass="ptl-body" id="toRender"> <h:dataTable value="#{flightMBean.flights}" var="f" id="flight_table" styleClass="table table-st ...

I'm currently attempting to incorporate the Material-UI InfoIcon into my code, but I'm unsure of how to properly integrate it within a TextField component

I am attempting to integrate the Material-UI InfoIcon into my TextField code, but I'm unsure of how to go about it. Here is the snippet of Material-UI code: <InfoIcon fontSize="small" /> This is where I would like to place it: <Grid item ...

Navigating properties and linking information in React

I'm currently tackling a project that requires me to pass data to two distinct functional components. While my axios call to the API appears to be functioning properly, along with setting the state using hooks, I am continuously encountering two pers ...

Using res.sendfile in a Node Express server and sending additional data along with the file

Can a Node.JS application redirect to an HTML file using the res.sendFile method from express and include JSON data in the process? ...

Find the class element that is nested under a parent element

Every day I collect daily lineups and need to determine if a team has not posted its lineup. If a team's lineup is missing, there will be a class element called lineup__no. My goal is to check each team and compile a list of the teams whose lineups ar ...

Interacting with Google Maps using Selenium IDE

I am facing challenges in creating a Selenium test case to automate the process of clicking on Google Maps, specifically for creating markers by single-clicking on the map. Issue with Record function in IDE Upon using the "Record" function, my mouse cli ...

Just started out with selenium-webdriver and learning how to navigate between different browser windows

Recently, I started utilizing selenium 2.0/web-driver for automating the testing process at my workplace. Currently, I have developed around 20 tests; however, each test opens a new browser window when executed. The challenge arises because I need the use ...

Issue with writing JSON data to a file in node.js

When I try to write JSON objects from the Twitter API to a file using the fs.appendFile method, all that gets written is "[object Object]". The JSON objects look fine when logged to the console, so I'm not sure why this is happening. For example, the ...

Best method to generate an element using any jQuery selector string

What I want to accomplish I am looking to create an element that matches any given selector string. Here's a quick example: var targetString = "a.exaggerated#selector[data-myattr='data-here']"; var targetEl = $(targetString); if(!targetE ...

Python/Selenium: Automating the process of clicking the "Next" button when it appears on the screen

In my current project, I am developing an automated test using Selenium with Python. The process involves displaying a window that shows tooltips on the screen. There are a total of 27 steps to complete the tutorial, each step requiring interaction with ...

Error in React Component: Array objects in response are not in correct order

My React app is receiving data via websocket, with a big object that contains game information. One of the properties is an array of player objects: { propertyX: "X", players: [{player1}, {player2}, {player3}], propertyY: "Y" } The issue I'm f ...

Establishing a Connection with Node/Express Routing via JavaScript

When developing a web application using HTML, JavaScript, and Node.js with Express, I often find the need to navigate between pages based on user actions. In HTML, one approach is to add an href link and then set up routes in my app.js file to handle the ...

Develop interactive pages in your mobile app with the help of PhoneGap

I developed a PhoneGap mobile application with a few pre-defined "html pages" (I emphasized the quotes, as they are not traditional html files). Utilizing the onsen-ui framework allowed me to consolidate all of these "html" pages into ONE index.html file. ...

Struggling to Create a T-Rex Game Bot with Selenium and Robot Class

I'm currently facing an issue with my T-Rex game bot. Initially, the code runs smoothly for a few seconds but then the game abruptly ends. In this project, I have employed Selenium and The Robot class. Below is a snippet of my code: public static voi ...

Experimenting with code within a window event listener function

I have a component in my AngularJS application that is functioning correctly. However, when it comes to test coverage, everything after the 'window.addEventListener('message',' part is not being covered. Should I create a mock object f ...

capture the alteration of text within an input field

Currently, I am utilizing the Joomla calendar feature to select a date. The HTML code for this functionality is displayed below. When you click on the image, a calendar will pop up allowing you to choose a date. Once selected, the popup closes and the date ...

Is there a way for me to extract a smaller segment from an ID label?

I am working on a web development project and I have a set of buttons within a specific section. Each button has an id in the format of #balls-left-n, where n ranges from 1 to 15. My goal is that when a user clicks on one of these buttons, I want to extra ...