Sending a text parameter to the JavaScript Executor within a Selenium framework

Although this question has been asked before, I have searched for multiple answers and have not found a solution to my specific problem.

if (driver instanceof JavascriptExecutor) {
        System.out.println("In try");
        ((JavascriptExecutor)driver).executeScript("document.getElementById('comment').value='"+line1+line2+"';");
    } else {
        throw new IllegalStateException("This driver does not support JavaScript!");
    }

I am using the above code to set values in a text area. The variables line1 and line2 are both strings.

The content printed from these variables is as follows:

  1. Root Cause Analysis: We have analyzed and discovered duplicate transactions present in our database. It seems that there was a problem with the feed returning pending transactions as posted, resulting in filings for two different dates.

We have filed UDC 7735 to perform necessary cleanup. 2. Fixes implemented to resolve the issue:

Despite not containing any quotation marks, I am encountering an error message stating:

Exception thread "main" org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected token ILLEGAL
at Object.InjectedScript._evaluateOn (<anonymous>:878:140)
...

When I attempted to use the sendKeys method of the driver, it worked but triggered automatic page submission or validation. This means I cannot use the sendKeys function to set the value.

If anyone can provide guidance on how to proceed, I would greatly appreciate it.

Answer №1

Give this a shot:

    if (driver instanceof JavascriptExecutor) {
            System.out.println("Attempting...");
            ((JavascriptExecutor)driver).executeScript("document.getElementById('comment').value=\'" + line1 + line2 + "\';");
    } else {
            throw new IllegalStateException("Sorry, but this driver doesn't have JavaScript support!");
    }

If you need to pass a string element to your script String, make sure to precede the single quotes with \. I hope this explanation helps.

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 is unable to find the specified element

Having an issue finding a specific element using python selenium, and here is the code snippet I am using: zframe = driver.find_element_by_xpath("/html/frameset/frameset/frame[5]") driver.switch_to.frame(zframe) findByXpath("/html/body/form/table/tbody/tr ...

Extract content from whole webpage including HTML, CSS, and JavaScript

Currently I am working on developing a webpage version control backup/log system. The goal is to automatically save a static copy of the webpage, including all its CSS and JavaScript files, whenever there are any changes made. I have already figured out h ...

Issue with Docker's depends_on flag not successfully handling dependencies between containers

My goal is to set up a Selenium hub, Chrome node, and Firefox node, and then run the test execution script in that specific order. I have the nodes depending on the hub, and the code depends on both the hubs. However, when I run docker-compose --build, it ...

The issue of Vue.js template errors within inline code

I am experimenting with using inline-template in combination with vue.js 2.0. This usage is within the context of Laravel blade 5.4: <users inline-template> <tbody> @foreach($users as $user) <tr> ...

Explore an array of objects to find and retrieve a value from the final matching object in JavaScript

I'm having difficulty retrieving the value for the last event that includes "SearchResults" in the scenario outlined below: Here is a schema of my datalayer where I am looking to gather information. Currently, I have managed to write the following co ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Java application unable to execute due to a missing Main

Currently delving into the world of Java for the first time, I am in need of running an application I recently downloaded from the internet. The said application is the "spinn3r" client, available for download at the following link: http://code.google.com/ ...

Selenium can be inconsistent when it comes to sending send_keys

I'm currently working on a script to login to Facebook, search for a specific webpage using the search bar, and select the top result. However, there seems to be an issue with the script not always sending keys to the search bar and failing instead. A ...

Display a modal dialogue with an image on the initial page load for each user

Working on a project with Angular 11, Angular material, and Bootstrap, I encountered an issue. I want to display a popup ad the first time a user visits the home page. The modal dialog is created using Angular material, and I have it in the ads component, ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

Filtering a table using jQuery based on the class or data attributes

Issue arises when selecting the first "Icon" shows "Not found", then opting for "Talisman" does not display. It should show "Not Found". Is this achievable? Add the classes f-Icon, f-Ring, f-Neck. Then search for the value by class. Select either "Icon R ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Identifying the Ctrl+C command in the Java Console

Developing a Console-Java game has brought up the need to save scores in a JSON file when Ctrl+C is pressed. The JSON file creation process itself works fine, but the challenge lies in detecting when Ctrl+C is pressed from the console in order to trigger t ...

Challenges with compiling Next.js with Tailwindcss and Sass

I recently created a simple template using Tailwind for my Next.js project. Normally, I rely on Tailwind's @layer components to incorporate custom CSS styles. However, this time I wanted to experiment with Sass, so I converted my globals.css file to ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

Searching for a specific element in jQuery by querying a string

I have a situation where an ajax request is made to send text using the POST method to another PHP page. This PHP page then converts the text into markdown format and sends it back. Here's an example of what it looks like: "<p>Meep, meep, <e ...

Save information to a server-side .xml file with the use of either JavaScript or PHP

I have a website built using HTML and JavaScript. Currently, I am successfully retrieving data from a server-side .xml file on the site. Everything is working perfectly! However, I am facing issues with allowing users to input data into a field and save ...

Dealing with special characters in Mustache.js: handling the forward slash

I have a JSON file that contains information about a product. Here is an example of the data: { "products": [ { "title": "United Colors of Benetton Men's Shirt", "description": "Cool, breezy and charming – this s ...

Having trouble with the jQuery toggle functionality not working as expected

I'm implementing a function where a div should increase in height and opacity when clicked, and then revert back to its original state when clicked again. I used the toggle function for this purpose, but the issue is that the button disappears when th ...

What is the best way to manage classNames dynamically in React with Material-UI?

I am wondering how to dynamically add and remove classes from an img tag. My goal is to change the image automatically every 2 seconds, similar to Instagram's signup page. I am struggling to achieve this using the material-ui approach. Below is a snip ...