JavascriptExecutor in WebDriver Failing to Function

As I attempt to populate text boxes on a website using JavaScript in Selenium WebDriver, my coworker shared this GitHub repository with me for speeding up the process.

However, upon running the program, it encounters an error at

((JavascriptExecutor)driver).executeScript("(function( window ) { 'use strict';"
. While it proceeds to traverse through each text box, it fails to add the intended text. Despite spending a considerable amount of time reviewing and comparing our code, my coworker and I remain baffled by the issue. Below is the snippet of my code along with the encountered errors.

Any assistance would be greatly appreciated.

Java Code

InputStream inputStream = ClientInformationComponent.class.getResourceAsStream("AutoFillClientInsuredComponent.js");

StringWriter writer = new StringWriter();

try 
{
    IOUtils.copy(inputStream, writer, "UTF-8");
} 
catch (IOException e) 
{
    e.printStackTrace();
}

for (ClientDAO client : clients)
{
    String script = writer.toString();

    try
    {
        if (driver instanceof JavascriptExecutor) 
        {
            // ERROR OCCURS HERE webdriver.components.ClientInformationComponent.fill(ClientInformationComponent.java:128)
            ((JavascriptExecutor)driver).executeScript("(function( window ) { 'use strict;'"    
                    + "var lastName = '" + client.getLastName() + "';"
                    + "var firstName = '" + client.getFirstName() + "';"
                    + "var middleName = '" + client.getMiddleName() + "';"
                    + "var suffix = '" + client.getSuffix() + "';"
                    + "var streetAddress = '" + client.getMemberAddress() + "';"
                    + "var city = '" + client.getMemberCity() + "';"
                    + "var zipCode = '" + client.getMemberZipCode() + "';"                          + "var birthDate = '" + client.getDateOfBirth() + "';"
                    + "var homePhoneNumber = '" + client.getHomePhone() + "';"
                    + script);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

JavaScript File

var document = window.document,
  fieldValueMap = {
        "LastName"              : lastName,
        "FirstName"             : firstName,
        "MiddleName"            : middleName,
        "Suffix"                : suffix,
        "MemberAddress"         : streetAddress,
        "MemberCity"            : city,
        "MemberZipCode"         : zipCode,
        "MemberZipCodeSuffix"   : memberZipCodeSuffix,
        "DateOfBirth"           : birthDate,
        "HomePhone"             : homePhoneNumber

  };

Object.keys( fieldValueMap ).forEach(function( name ){

    var input = document.querySelector( "form input[name='" + name + "']" )
                    || document.querySelector( "form select[name='" + name + "']" )
        || document.querySelector( "form textarea[name='" + name + "']" );

    input && input.type !== "hidden" && ( input.value = fieldValueMap[ name ] );
});

})( window );

Error Log

org.openqa.selenium.WebDriverException: JavaScript error (WARNING: The     server did not provide any stacktrace information)
Command duration or timeout: 47 milliseconds
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23    20:02:37'
System info: host: 'COL-ISD-D56345', ip: '10.8.11.30', os.name: 'Windows 7',   os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_65'
Session ID: 10b4929d-001c-412c-94bc-ce9d006b6dd0 
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{platform=WINDOWS, javascriptEnabled=true,   elementScrollBehavior=0, ignoreZoomSetting=false, enablePersistentHover=true,   ie.ensureCleanSession=false, browserName=internet explorer,   enableElementCacheCleanup=true, unexpectedAlertBehaviour=accept, version=9,   ie.usePerProcessProxy=false, ignoreProtectedModeSettings=false,   cssSelectorsEnabled=true, requireWindowFocus=false,   initialBrowserUrl=http://localhost:22000/, handlesAlerts=true,   ie.forceCreateProcessApi=false, nativeEvents=true, browserAttachTimeout=0,   ie.browserCommandLineSwitches=, takesScreenshot=true}]
Command duration or timeout: 356 milliseconds
Build info: version: '2.44.0', revision:   '76d78cf323ce037c5f92db6c1bba601c2ac43ad8', time: '2014-10-23 13:11:40'
System info: host: 'COL-ISD-D56444', ip: '10.8.12.163', os.name: 'Windows  7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_45'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities [{browserAttachTimeout=0, enablePersistentHover=true,  ie.forceCreateProcessApi=false, ie.usePerProcessProxy=false,  ignoreZoomSetting=false, handlesAlerts=true, version=9, platform=WINDOWS,  nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0,  webdriver.remote.sessionid=863d35b9-ff0d-4b83-b4e0-983d9272353d,  ie.browserCommandLineSwitches=, requireWindowFocus=false, browserName=internet  explorer, initialBrowserUrl=http://localhost:22000/, takesScreenshot=true,  javascriptEnabled=true, ignoreProtectedModeSettings=false,  enableElementCacheCleanup=true, cssSelectorsEnabled=true,  unexpectedAlertBehaviour=accept}]
Session ID: 863d35b9-ff0d-4b83-b4e0-983d9272353d 

Answer №1

We have identified the root cause of the problem. Our current browser is IE 9, and according to this documentation, if the <!DOCTYPE html> declaration is missing, IE 9 will default to displaying the page in Quirks Mode or Compatibility Mode.

To ensure proper rendering in IE 9 and avoid Quirks Mode, including the <!DOCTYPE html> declaration is necessary. Additionally, adding a meta tag like

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
allows for emulating specific versions of IE as needed with parameters such as content="IE=EmulateIE# or content=IE#.

The challenges we faced stemmed from certain JavaScript methods not being compatible with older IE versions. While attempting to modify some methods to accommodate these limitations, we encountered increasing issues with compatibility due to reliance on unsupported features across older IE versions.

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

Using Typescript to declare types for an object that is capable of generating an outcome

If I have an object structured like this let obj = { property1:()=>{ return Date()} // for example, it doesn't have to be a date property2:()=>{ return 1} } Now, I want to convert this to the following type structure { property1: ...

Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when send ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Search for an element in an array using a query in MongoDB

[MONGO] Here is a collection of different places with their corresponding tags: [ { item: "journal",tags: ["blank", "red","blue","yellow"]}, { item: "notebook",tags: ["red", "pink","green"]}, { item: "paper", tags: ["red", "blank", "plain","bl ...

Leveraging Mongodb's aggregate feature to calculate the overall quantity of a specific product that has been ordered across all

Recently delving into the realm of javascript, I am currently tackling a dashboard project that requires displaying the total quantity of each product ordered. Although I have successfully defined a variable 'qty' to represent the quantity of an ...

Dropping challenging shapes in a block-matching game similar to Tetris

I'm currently working on a game similar to Tetris, but with a twist. Instead of removing just one line when it's full, I want to remove all connected pieces at once. However, I've run into a roadblock when trying to implement the hard-drop f ...

Is it accurate to consider all JavaScript code and variables as inherent properties of an execution context?

It's worth considering that everything in JS code can be viewed as a property of an execution context, whether it's a global, function, or eval() execution context. Why is this the case? Each execution context has its own unique lexical and v ...

Flashing white screen when transitioning between pages on phonegap iOS system

I'm currently using phonegap for my iOS application project. Interestingly, I've noticed a slight white flicker/flash when navigating between pages in the app. To address this issue, I have refrained from using jquery mobile and instead relied ...

Creating a personalized .hasError condition in Angular 4

I am currently in the process of modifying an html form that previously had mandatory fields to now have optional fields. Previously, the validation for these fields used .hasError('required') which would disable the submit button by triggering a ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...

Tips for extending hover duration in CSS

a:hover + #menu { display: block; position: fixed; } My CSS for a hover effect is causing the menu to disappear quickly once I move the mouse away. What steps can I take to fix this issue? Would utilizing JavaScript provide a better solution, and if so, ...

Using JavaScript and the Firefox browser, learn how to easily highlight an element with Selenium-WebDriver

I am struggling with creating a valid function to highlight specific elements on a webpage. As a beginner in coding, I suspect that the issue may either be related to my environment setup or a lack of knowledge about JavaScript/Selenium features. I am wri ...

Analyzing registration details stored in an array against user login credentials

With two buttons available - one for sign up and the other for log in, my goal is to gather input form values from the sign-up section into an array. Following this, I aim to compare the user input from the sign-up with that of the log-in, informing the us ...

Having trouble choosing options within Material UI's Autocomplete Component?

I'm having trouble selecting the options displayed in MUI's autocomplete component. It seems that using renderOption is causing this issue. I want to show an image along with the title in the component options, but without using renderOption, I h ...

Function for editing a button in an AngularJS single page application

I am a beginner in AngularJS and I'm currently working on a project to create a single page application for tracking expenses. However, I'm facing some challenges with my code. Although I have successfully implemented most of the functions, I am ...

Tracking user session duration on a React Native app can be achieved by implementing a feature that monitors and

I'm currently focusing on tracking the amount of time a user spends on the app in minutes and hours, and displaying this information. I have successfully implemented the functionality to count minutes, but I am struggling to figure out how to track wh ...

Locate the offset parent within an element using Xpath

I am facing an issue with my Selenium test that involves a specific XPath query. "//tr[td/strong='Riparian 2m Ungrazed - RBS' and td/button[@id='btnDeleteOption_WG']]" Despite successfully retrieving the desired element, an additional ...

What is the best method for pulling out two specific lines from a lengthy paragraph containing 10 lines of text?

I need help with extracting specific information from a block of text. Out of 10 lines, only two lines are essential - those that contain the "Scannable ID" and its corresponding randomly generated value on the right side. Line 1 Line 2 Line 3 . . . Scann ...

Using Promise.all to loop through generators is not a supported operation

Exploring the world of Javascript generators and promises, it becomes clear that they work well together. To effectively navigate through a coroutine of promises using Promise.coroutine from the Bluebird library simplifies executing promises in the correct ...

What is the equivalent command in MongoDB?

Just starting out with MongoDB and I'm curious about the equivalent of this SQL statement: SELECT * FROM users WHERE CONCAT(firstName, ' ', lastName) LIKE CONCAT('Walter Whi', '%') ...