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

What is the best way to access a database connection throughout an entire node.js application?

In my application's app.js file, I establish a connection to mongodb using the monk module. var express = require('express'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var mong ...

When utilizing Google Analytics in conjunction with Next.Js, encountering the error message "window.gtag is not

Encountering an error on page load with the message: window.gtag is not a function Using Next.js version 14.0.4. All existing solutions seem to hinder data collection, preventing the website from setting cookie consent correctly. I am uncertain about the ...

Change occurring within a cell of a table that has a width of 1 pixel

In the code snippet below, there is a transition inside a table cell with a width of 1px to allow it to wrap its content. However, the table layout changes only at the end or beginning of the transition: var animator = document.getElementById("animator" ...

Adjust Mui Autocomplete value selection in real-time

I have implemented Mui AutoComplete as a select option in my Formik Form. <Autocomplete disablePortal options={vendors} getOptionLabel={(option) => option.vendor_company} onChange={(e, value) => {setFieldValue("vendor_id", value. ...

Transforming Color with JQuery on the Fly

Check out this Jquery script that gradually changes the color of an object from (0, 0, 0) to (255, 255, 0). $(document).ready(function(){ var r = 0; var g = 0; changeColor(r, g); }); function changeColor(r, g){ var newColor = "(" + r + ", ...

What is the best method to retrieve a nested JSON property that is deeply embedded within

I am facing an issue with storing a HEX color code obtained from an API in a Vue.js app. The object app stores the color code, for example: const app = {"theme":"{\"color\":\"#186DFFF0\"}"}. However, when I try to access the color prope ...

On Linux systems, Node.js in JavaScript interprets strings as objects only

I'm encountering an issue with my Discord.io bot. I am attempting to run it on a Linux server, but the Linux version of Node.js keeps treating the contents of a string as a separate object, leading to the following TypeError: TypeError: Object IT&apo ...

What steps can I take to make sure that all Selenium webdrivers created by my program are properly terminated upon the program ending?

Is there a way to ensure that all new instances of webdrivers are terminated automatically when my program ends? This means making sure the new process will close even if the program crashes or if an explicit .quit() is not added in the code. Edit: One po ...

Tips on implementing Dynamic arrays in the useEffect hook within React applications

Does anyone have experience with using a dynamic array as input in the dependency array of the useEffect hook? I'm encountering an issue where the array is being passed as a string and therefore not triggering the hook correctly. const [formData,setFo ...

Is the branch of ExtJS 4.1 TreeStore lazy loading extending?

I am working on implementing lazy loading of tree branches in an MVC application using extjs4.1. The branches are located on different URLs and I have faced several challenges along the way. Unfortunately, at this point, the branching functionality is not ...

Automating the process of clicking on each link and opening them in new tabs with Selenium Ruby

I am looking to modify my code in order to open all clicked links in new browser tabs once the page loads using driver.get "http://www.example.com". Despite receiving answers from previous questions, the solutions provided have not met my expectations. Bel ...

What is the best way to prevent a draggable div from moving past the edge of the viewport?

My situation involves a draggable div that functions as a popup window when a specific button is clicked. However, I noticed that dragging the div to the end of the viewport allows me to drag it out of the visible area, causing the body of the page to expa ...

Encounter a Socket.io connection error due to net::ERR_CONNECTION_REFUSED when trying to access from multiple devices

I'm having trouble with other people's computers accessing my test chatting application. When they try to connect, they encounter this error: localhost:3000/socket.io/?EIO=4&transport=polling&t=Oi2Ko0C:1 Failed to ...

Creating a universal header for all webpages in Angular JS by dynamically adding elements using JavaScript DOM manipulation techniques

I have successfully created a json File containing an array of "learnobjects", each including an id, name, and link. Check out my plnkr example var myMessage = { "learnobjects": [{ "id": "1", "name": "Animation-Basics", "link": "animation_bas ...

How can you confirm the validity of a dropdown menu using JavaScript?

<FORM NAME="form1" METHOD="POST" ACTION="survey.php"> <P>q1: How would you rate the performance of John Doe? <P> <INPUT TYPE='Radio' Name='q1' value='1' id='q1'>1 ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

If you click outside of a Div element, the Div element will close

I am looking for a way to implement a function that will hide a specific div when I click outside of its area. The div is initially set to Position: none and can be made visible using the following function: Div Element: <div id="TopBarBoxInfo1" oncli ...

Binding Data to Arrays in Polymer

I'm currently diving into the world of Polymer. My goal is to connect an array with my user interface in a way that allows for dynamic updates. Each object within the array contains a changing property, and I want my UI to reflect these changes accord ...

Error: PHP is showing an undefined index error when trying to decode JSON, even though the value

I am feeling quite puzzled. I transferred a key value pair object from jQuery to PHP and successfully alerted it back out. However, when I visit the PHP page, it indicates that the data is either null or an undefined index. Here is my jQuery code: $(&ap ...

The useEffect hook fails to recognize changes in dependencies when using an object type obtained from useContext

Utilizing the useContext hook to handle theme management in my project. This is how the ThemeContext.js file appears: "use client"; import { createContext, useState } from "react"; let themes = { 1: { // Dark Theme Values ...