Introducing a custom JavaScript function using Selenium in Java

I am faced with the challenge of incorporating a dynamic function after the page has loaded. This need arises because the function name is dependent on a variable obtained through parsing HTML. Presently, my approach involves:

Context: Using Selenium 3.3.1 with PhantomJS 1.9.8

((JavascriptExecutor) driver).executeScript(" eval('function getVoteX1() { return 1; }')");
String testScript = (String)((JavascriptExecutor) driver).executeScript(" getVoteX1()");
System.out.println(testScript);

However, upon executing this code, an error is thrown :

Caused by: org.openqa.selenium.WebDriverException: {"errorMessage":"Can't find variable: getVoteX1","request":{"}

It is important to note that while I currently use 'getVoteX1' as a placeholder, it will eventually be substituted with another variable in a more complex scenario.

Answer №1

Link the new function to the window element, which is similar to creating a global variable:

((JavascriptExecutor) driver).executeScript("window.getVoteX1 = function() { return 1; }");
String testScript = (String)((JavascriptExecutor) driver).executeScript(" getVoteX1()");

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

Choose the right Vue.js component for optimal performance

I have a primary element within which there is a secondary element with vue.js 2.0. The issue arises when the secondary element relies on methods from the primary element. Here's an illustration: Vue.component('primary-element', { tem ...

The TypeScript error reads: "An element is implicitly assigned the 'any' type because an expression of type 'any' cannot be used to index a specific type."

[Hey there!][1] Encountering this TypeScript error message: { "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ 0: { image: string; title: string; text: string; }; 1: { ...

Angular: Built-in solution for managing unhandled HTTP errors

I have implemented a default handler for handling http errors in my angularjs app as shown below: myapp.config([ '$httpProvider', function($httpProvider) { $httpProvider.responseInterceptors.push('errorInterceptor') }]) The errorI ...

Check to see if each individual item includes an element that utilizes protractor

I am attempting to verify whether each of the items with the class name .elem1 contains another element with the class name .elem2. I have tried the following code, but it does not produce the desired outcome: expect(element.all(by.css('.elem1') ...

The NodeJS script is slowly consuming more and more memory

During my recent debugging session, I encountered a memory issue with a small to medium-sized Node.js app. Every time I utilize Chrome debug tools, the memory usage gradually increases by approximately 1mb every 15 minutes, even though I have not been able ...

Update the information within the Nuxt.js middleware

Can the response content be altered through middleware without changing the URL of the page? I want to clarify that I am not looking to redirect to a different route. ...

What sets Codeception apart from peridot paired with php-webdriver?

Looking to implement acceptance tests for my company's PHP legacy app. Considering using Selenium WebDriver, but unsure about the best testing framework. Potential Solution 1 Our unit tests are in Peridot PHP, and it seems feasible to use WebDriver ...

Why does npm/yarn claim that the "license" in my package.json is missing when I have it listed?

Whenever I run yarn install, a warning pops up indicating that there is no license field, despite having defined one as follows: $ jq . package.json { "name": "license-example", "version": "1.0.0", "main": "index.js", "license": "UNLICENSED", " ...

Utilize Angular to send a request to a DJANGO REST API, retrieve the data, and display the results in a DJANGO view

I'm currently facing an issue where I have a search input field on my main index page. When the user inputs a query, it gets sent to the Django REST API which responds with data in JSON format. Using Angular's ng-repeat, I can iterate through the ...

Accessing information from YouTube Data API using Java and Spring Boot

I have been working on extracting title, videoId, and description data from videos fetched using the YT Data API. Although I managed to retrieve the data in a JSON-like format (which is actually a LinkedHashMap when checked with getClass()) in Postman and ...

The element remains stationary within the canvas

I am attempting to relocate an element within a canvas, but for some reason, it is not working. Here is the code I have tried: Actions actions = new Actions(driver); actions.moveToElement(flowCanvas, 434, 177); actions.clickAndHol ...

No data is being returned by the Jquery Ajax function

I am experiencing an issue with a Jquery Ajax call in my code: $('body').on('click', '#btnPopulate', function() { alert(getTree()); }); function getTree() { var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewMode ...

There seems to be an issue with the functionality of $apply in angular when used in conjunction with form

I've encountered an issue with my code where the form submission doesn't work properly unless I wait a few milliseconds before submitting. The problem seems to be related to setting the value of a hidden field called paymentToken. My goal is to ...

Executing multiple child processes in a loop with asynchronous operations and collecting the output after the loop concludes

Here's a snippet of code I've been working on... const { exec } = require('child_process'); const Main = async () => { const result = await RetrieveAllItems(); console.log('output', result); }; const RetrieveAllI ...

Selenium browser automation: troubleshooting mouseover and dropdown menu issues when hovering in and out of the browser

System Requirements: Operating System: Windows 7; Selenium Version: 2.39.0; IDE: Java - Eclipse I am currently using Selenium to automate testing on a web application across three different browsers - Chrome, IE9, and Firefox. The web app features a menu ...

Encountering difficulties while running ng-serve

I ran into an issue while using angular cli, specifically this error message: ERROR in multi script-loader!./src/assets/vendors/by_bower/jquery/dist/jquery.js To troubleshoot, I followed these steps: npm install -g @angular/cli; npm install ng serve ...

Determine the type of element existing in the table cell

Currently, I am utilizing protractor to iterate through table cells in an attempt to verify the presence of a checked checkbox. var elements = element.all(by.css(columncssname)); elements.each(function (cell, index) { <--need to confirm if check ...

Automatically retrieve the PDF file by obtaining the file path string from an API request

Is it possible to automatically download a PDF in the browser instead of just returning a file path string? Here's the code snippet I have: getMergedPDF(filesToUpload: Array<string>) { return this.http.post<string>('http://localh ...

Display information on a table using AJAX within the current webpage

I am encountering an issue with ajax on the same page. Below is my code: $.ajax({ type: "POST", url: "test.php", dataType: 'json', data: {}, success: function (data) { ...

The value retrieved from redux appears to be varying within the component body compared to its representation in the return

Trying to fetch the most recent history value from the redux store to pass as a payload is presenting a challenge. When submitting a query, the history updates and displays the latest value within the map() function in return(), but when checking at // CON ...