Utilizing a JavaScript variable in Firefox with Java WebDriver: A guide

The main objective is to retrieve the JavaScript element authKey in Java code. Below are the codes:

index.html:

...
      <script type="text/javascript">

        var params = {
            authKey: "abc"
        };

        Main.init("#content", params);
    </script>
...

main.java:

public static void main(String[] args) throws InterruptedException {

        WebDriver d = new FirefoxDriver();
        d.get("***/index.html");
   //     System.out.println(" var " + d.findElement(By.xpath("/html/body/script[3]")));
        Thread.sleep(3000);
        JavascriptExecutor jse = (JavascriptExecutor) d;
//        System.out.println(jse.executeAsyncScript("document.URL"));
        Object val = jse.executeScript("return params.authKey;");
        d.quit();
    }

Each time, I am encountering an issue like this:

Exception in thread "main" org.openqa.selenium.JavascriptException: ReferenceError: **params is not defined**
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'Mikhails-MacBook-Pro.local', ip: '10.10.20.139', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_111'
Driver info: org.openqa.selenium.firefox.FirefoxDriver

I have attempted various methods to retrieve the authKey parameter, without using return or as a function, yet nothing seems to work. Can anyone provide assistance with this?

Thank you in advance.

UPD: The solution is effective, but I am still interested in finding a native JS solution specifically for obtaining the params.authKey parameter, as there may be numerous params in the future.

Answer №1

There may be a scope problem depending on the version of Firefox. It is possible that your variable is enclosed within window.wrappedJSObject.

You can attempt the following solution:

let authKey = driver.executeScript(
  "return (window.params || window.wrappedJSObject.params).authKey;");

Answer №2

If you only have one script tag, or if this is the first one in the code.

    WebElement scriptElement = driver.findElement(By.tagName("script"));
    System.out.println(scriptElement.getAttribute("innerHTML"));
    System.out.println(scriptElement.getAttribute("innerText"));

The output using either of the above two attributes should be:

var params = {
     authKey: "abc"
};

Main.init("#content", params);

To extract the authKey from the output...

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

Organize your blog content by utilizing post IDs as the designated id attribute

What is the best way to format blog posts and comments in HTML so that I can easily manipulate them later using jQuery/Javascript for tasks like updating, deleting, or making Ajax calls? I am considering using the IDs (primary keys in the database) of the ...

Utilizing a Static Image Path Prop in React JS: A Step-by-Step Guide

My Main Component import React from "react"; import TopModal from "./components/topModal"; // Passing productImage to the Child Component import productImage from "../../../../../../assets/images/juices.jpg"; import { makeS ...

Updating Bootstrap 5.3 Modal to Have a Fixed Backdrop when Opened (Using JavaScript/JQuery)

Is there a way to change the backdrop of an open modal to 'static' using jQuery or JavaScript? I want to prevent the user from closing the modal by clicking outside after they have clicked the 'Submit' button on the modal. I've tri ...

Can TypeScript automatically deduce keys from a changing object structure?

My goal here is to implement intellisense/autocomplete for an object created from an array, similar to an Action Creator for Redux. The array consists of strings (string[]) that can be transformed into an object with a specific shape { [string]: string }. ...

Integrating Asp.Net Core for server-side functionality with React for client-side interactions

I have started a simple Asp.Net default project in Visual Studio 2015 using the template: ASP.NET Core Web Application (.NET Core) / Web Application, No Authentication. Following that, I created a package.json file to load all the necessary packages for R ...

Class with an undefined function call

Currently, I am working with angular2 and TypeScript where I have defined a class. export class Example{ //.../ const self: all = this; functionToCall(){ //.. Do somerthing } mainFunctionCall(){ somepromise.then(x => self.fu ...

Having trouble with Pie Chat not displaying on my browser while working on D3 integration with basic HTML

I am struggling to get my Pie chart created using D3.JS to show up when I load my file in Chrome or any browser (index.html). It only displays the title without the actual pie chart. I'm not sure where the issue lies and why my pie chart is not appea ...

angular and node: troubleshooting the $http.get error

I have encountered an issue with the $http.get instruction. Without it on the main page, I receive a result of "random 46" which is correct. However, when I include $http.get, I get a result of "random {{ number }}". How can this problem be resolved? -se ...

jQuery isn't activating when using the on("click") event

Presented here is a genealogical tree, starting with a user (the JavaScript Fiddle below). This user has 2 options available - one functioning properly while the other is currently inactive. The operative option (+) opens a pop-up where you can add a "cou ...

Expanding upon the Ember.js Model's save functionality

I have incorporated promise-based code (MyLib) that needs to execute on every model save by extending the save function: DS.Model.extend save: -> parentSave = @_super.bind this, arguments... deferred = Ember.RSVP.defer() MyLib.func().t ...

Steps to Create an HTML Text Box that cannot be clicked

Does anyone know of a way to prevent a text box from being clicked without disabling it or blocking mouse hover events? I can't disable the text box because that would interfere with my jQuery tool tips, and blocking mouse hover events is not an opti ...

What is the best way to extract the innerHTML of every button and exhibit it in a text box?

How can I create a simpler JavaScript code for clicking buttons to input letters into a text box? Instead of creating getElementByID for each button, is it possible to use some kind of loop? <div id="alpha" > <br/> <div align="cente ...

Creating a cookie in Django to save a list view with basic Javascript techniques

I've implemented a feature in my Django view where users can toggle between two different "views" of a list using a toggle button. One option displays a map with markers and information, while the other option shows the same information in a list form ...

What is the best method to transfer information from a What You See Is What You Get editor to a database using Vue.js?

I have recently started using the Vue2Editor in order to streamline my process of sending text and image data to my Firebase database. However, I am encountering an issue where the entered data is not being added successfully. Previously, with traditional ...

Updating React Native using setState is not possible

In my React Native application, there is a function that deletes an item: delete(index){ this.setState({deletedIndex:index, cachedCart:this.state.Cart, Cart: this.state.Cart.splice(index,1) }, function(){ console.log(th ...

Is an Ajax request always encountering errors when communicating with the server-side Jersey/Java RESTful web service and not responding in JSONP format?

My Jersey API (restful web service) is very simple and works fine with my android application. Now, I'm building a web backend to manage data. However, every time I make calls with ajax, the response ends up in the "error" section. Oddly enough, when ...

Client-Side Isomorphic JS: A Guide to Using HTTP Requests

Seeking advice on data population for isomorphic flux apps. (Using react, alt, iso, and node but principles are transferable) In my flux 'store' (), I need to fetch data from an api: getState() { return { data : makeHttpRequest(url) ...

Issue with Spring Boot project not updating data from database

Recently, I have been delving into a full stack application project using Angular and Spring Boot for the first time. Following a comprehensive tutorial has guided me through this journey. Starting with a project downloaded from , I included various depen ...

Mongoose encountering an issue with undefined properties (specifically 'prototype') and cannot read them

I am currently using Mongoose 7.0.1 on Next JS 13.2.2 and React 18.2.0. After tirelessly searching for a solution to my problem, I am still struggling with connecting to a MongoDB. Every time I try to import mongoose into my project for the connection, an ...

Deleting items from the DOM using JavaScript

I am retrieving all the list elements from a menu in order to eliminate the ones that I do not want. let prodMenu = document.getElementsByClassName("productMenu-category"); for (let i = 0; i < prodMenu.length; i++) { if(i > 0 && ...