Run JavaScript code with Selenium WebDriver prior to calling get() in Java

Currently, I am attempting to use Selenium in Java to access a web page. Unfortunately, the site is returning an error message:

Exception in thread "main" org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "require" is not defined.

After consulting with a front end developer, I was advised to load a specific JavaScript script before the page loads. The script in question is called require.js, and I was able to locate it at https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js

I am currently using htmlunit-driver 2.28. I have noticed that when initializing the driver as follows:

HtmlUnitDriver driver =new HtmlUnitDriver(true);

An option becomes available:
driver.executeScript(script, args)

This option is missing when using
WebDriver driver =new HtmlUnitDriver(true);

Although I can potentially work around this issue by using HtmlUnitDriver (as my code is already in production for other projects using WebDriver), I am unsure how to utilize the executeScript function to pass a URL for the script.

If anyone could provide guidance on injecting this into my WebDriver, I would greatly appreciate it. Thank you!

Answer №1

To customize the WebClient utilized by the HtmlUnitDriver, some adjustments need to be made. By default, the option throwExceptionOnScriptError is set to true. However, all browsers tend to stop processing JavaScript if an (unhandled) exception occurs. If I understand correctly, your page also throws this exception when loaded in a real browser; therefore, you need to:

  1. Turn off throwExceptionOnScriptError
  2. Communicate with the page/JavaScript developer regarding code quality

Here's a sample code snippet:

WebDriver driver = new HtmlUnitDriver(true) {
    @Override
    protected WebClient modifyWebClient(WebClient client) {
        client.getOptions().setThrowExceptionOnScriptError(false);
        return client;
    }
};

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

Ways to retrieve the related file in Angular service files?

I am looking to retrieve an array from another service file (chart-serv.js) in my return-serv.js service file using AngularJS. How can I reference the dependent file enclosed within double braces [ ], in line 1? return-serv.js var app = angular.module(& ...

Emphasize the letter by pressing the shift key along with either the left arrow

When the right and left arrow keys are pressed, my HTML element currently only highlights the next letter when the shift key is also pressed. How can I modify it to highlight all the letters in the word when the shift key and the right or left arrow keys a ...

optimal techniques for integrating an AJAX framework

Seeking advice on best practices for implementing AJAX framework and handling unique situations such as: Dealing with session timeouts during AJAX calls (e.g. redirect to login page, display error message, etc.) Handling server exception ...

Efficiency of Spring Data JPA batch insert operations can be improved

Trying to process a large Excel file with over 700K records and batch insert them into a MySQL database table. Excel parsing is quick, allowing entity objects to be extracted into an ArrayList within around 50 seconds. Utilizing Spring Boot and Spring Da ...

Searching for a mobile element using Appium xpath by matching the @text attribute with a regular expression (regex) - here's how!

I'm currently working on automating Android apps using Selenium-Appium (Java) and I am facing a challenging issue that requires your expertise: There is an element in the app that does not have any ID or ACCESSIBILITY ID configured. However, I have o ...

During my selenium testing, an error has emerged

[1.504][SEVERE]: Failed to bind() with error code 98: Address already in use Nov 20, 2017 1:03:49 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Driver dialect detected as OSS ...

The creation of the Angular project was unsuccessful due to the outdated circular-json dependency

After attempting to create a new Angular project with the command: ng new hello-world I encountered an error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d6dcc7d6c0d9d4c798dfc6dadbf5859b809b8 ...

Unable to set $_POST value when using $.ajax post request

I am a beginner in the world of PHP and JavaScript, and I have encountered an issue where I need to make changes to values in an XML document that has been read in. Specifically, I have an HTML Select element that was dynamically generated by PHP code. fu ...

Obtain the current time for a specific user

I'm currently struggling with obtaining the accurate 'trusted' user time, in order to prevent any cheating through manipulation of their computer's clock. Whether I utilize a basic date object, moment timezone, or even Google timezone ...

Omit child DIV element in JavaScript and the Document Object Model

I have a situation with two div elements. One is <div class="card" id="openWebsite"> and the other is a sub-division <div class="card__btn"> Here's the issue: When someone clicks on the main div, they get red ...

Issue with VueJs and ChartJs not displaying custom options when making an API call

Having trouble populating my chart with data from the API. Despite setting extraOptions for my chart, it defaults to default options when rendered. Here is the component code: import { Bar, mixins } from 'vue-chartjs'; export default { name: ...

Minimize the entire project by compressing the .css, .js, and .html files

After recently incorporating Grunt into my workflow, I was thrilled with how it streamlined the process of minifying/concatenating .css files and minifying/uglify/concatenating .js files. With Grunt watch and express, I was able to automate compiling and ...

What is the best way to transfer variables from an ng-template defined in the parent component to a child component or directive?

Is there a way to pass an ng-template and generate all its content to include variables used in interpolation? As I am still new to Angular, besides removing the HTML element, do I need to worry about removing anything else? At the end of this ...

I am having difficulty accessing the desired website on a remote PC using a compressed Selenium executable file

Recently, I developed a Python script combined with Selenium to automate the login process on a website. It worked perfectly on my personal computer. However, when I compressed the script into an executable file (.exe) to run it on a remote PC, it failed t ...

Checking the types of arrays does not function properly within nested objects

let example: number[] = [1, 2, 3, 'a'] // this code block correctly fails due to an incorrect value type let example2 = { demo: 1, items: <number[]> ['a', 'b'], // this code block also correctly fails because of ...

Issue: Error message - Unhandled promise rejection: NodeInjector error - ControlContainer not found

I'm having trouble validating a form and encountering an error. I tried implementing the suggestions provided in the following threads without success: Getting error suddenly in Angular Error: NodeInjector: NOT_FOUND [ControlContainer] Using forms i ...

What is the process for enrolling an app user in OneSignal topic subscriptions?

I have integrated OneSignal.com platform for push notifications into my app. I am interested in categorizing app users based on their preferences such as weather, sports, and technology. While Firebase SDK offers a method to subscribe users to specific top ...

Use JavaScript to change the text of a hyperlink to @sometext

<li class="some-class one-more"><label>twitter:</label> <a href="https://twitter.com/sometext?s=09" target="_blank" rel="noreferrer noopener">https://twitter.com/sometext?s=09</a> < ...

Using Vue.js to conditionally render data in a v-for loop

Below is the code snippet I am working with: <article class="project-card" v-for="item in en.projects" Additionally, here are some import statements: import fr from '../assets/datas/fr.json' import en from '../assets/datas/en. ...

Implementing NPM commands in Jenkins using shell scripting

Whenever I attempt to run the "npm" command, I encounter a syntax error. Users/Shared/Jenkins/Home/workspace/projectName/npm test ^^^^ SyntaxError: Unexpected identifier This is the Jenkins Build shel ...