Can WebDriver (HtmlUnit, Ruby bindings) be configured to bypass JavaScript exceptions?

When attempting to load the page, HtmlUnit throws an exception and crashes my test.

caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => true)
driver = Selenium::WebDriver.for(:remote, :desired_capabilities => caps)
driver.navigate.то url

ReferenceError: "x" is not defined. (net.sourceforge.htmlunit.corejs.javascript.EcmaError)

No errors occur when using a Firefox driver.

caps = Selenium::WebDriver::Remote::Capabilities.firefox

You can also resolve this issue by disabling JavaScript for the HtmlUnit driver.

caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => false)

If you are unable to modify the code on the test page to fix the problem, you may need to either ignore it or find a way to utilize the Firefox JavaScript Engine instead of the default HtmlUnit JavaScript Engine.

Is there a solution that does not involve changing the test page's code?

Update: I attempted using Capybara + WebKit as an alternative to Selenium + HtmlUnit, which worked fine without any errors. However, I still prefer to address the issue without switching frameworks.

Answer №1

Java Specific: The most recent update of the WebClient library (which is encapsulated by HTMLUnitDriver) has rendered the method

client.setThrowExceptionOnScriptError(false)
deprecated. If you are extending HTMLUnitDriver, you will now need to override the modifyWebClient method like so:

public class MyHtmlUnitDriver extends HtmlUnitDriver {

...

 @Override
    protected WebClient modifyWebClient(WebClient client) {
        //currently does nothing, but may be changed in future versions
        WebClient modifiedClient = super.modifyWebClient(client);

        modifiedClient.getOptions().setThrowExceptionOnScriptError(false);
        return modifiedClient;
    }
}

Answer №2

Upon examining the source code of the HtmlUnitDriver, it appears that there is no straightforward way to customize the specific behavior you are looking to modify. One potential solution would involve making changes to the Selenium server by patching and recompiling it, although this may not be a viable option for everyone. The following line can be added:

--- HtmlUnitDriver.java 2012-01-05 17:45:22.779579136 +0100
+++ HtmlUnitDriver.java 2012-01-05 18:14:51.415106195 +0100
@@ -255,6 +255,7 @@
     WebClient client = newWebClient(version);
     client.setHomePage(WebClient.URL_ABOUT_BLANK.toString());
     client.setThrowExceptionOnFailingStatusCode(false);
+    client.setThrowExceptionOnScriptError(false);
     client.setPrintContentOnFailingStatusCode(false);
     client.setJavaScriptEnabled(enableJavascript);
     client.setRedirectEnabled(true);

Answer №3

After some experimentation, I managed to find a solution using the

HPUnit_Extensions_Selenium2TestCase
v1.4.0. Here is how I achieved it:

class TestConfiguration extends PHPUnit_Extensions_Selenium2TestCase
{
    public function setUp()
    {
        $this->setHost(<your-host>);
        $this->setPort(<your-port>);
        $this->setDesiredCapabilities(Array("javascriptEnabled"=>"false"));

Answer №4

Answer provided by @Vitaly

    import org.openqa.selenium.htmlunit.HtmlUnitDriver;
    import com.gargoylesoftware.htmlunit.WebClient;
    import java.util.logging.Logger;
    import java.util.logging.Level;

    public class CustomHtmlUnitDriver extends HtmlUnitDriver {
        protected void customizeWebClient() {
            /* Disabling annoying htmlunit warnings */
            Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
            WebClient newWebClient = getWebClient();
            newWebClient.getOptions().setThrowExceptionOnScriptError(false);
            newWebClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            newWebClient.getOptions().setPrintContentOnFailingStatusCode(false);
            customizeWebClient(newWebClient);
        }
    }

Answer №5

In my experience in the .NET environment, I encountered a similar issue.

To work around this problem in C#, I utilized reflection and crafted an extension method:

public static void HandleScriptErrors(this HtmlUnitDriver driver, 
                                        bool handleErrors)
{
    object webClient =  driver.GetType().InvokeMember("_webClient",
                                    BindingFlags.GetField | 
                                    BindingFlags.NonPublic | 
                                    BindingFlags.Instance, null,
                                    driver, new object[0]);

    webClient.GetType().InvokeMember("handleErrorScripts_",
                                        BindingFlags.SetField | 
                                        BindingFlags.NonPublic | 
                                        BindingFlags.Instance,
                                        null, webClient, 
                                        new object[] {handleErrors});
}

Answer №6

This technique will silence any logging mechanism permanently!

static void setFinalStatic(Field fld, Object newVal) throws Exception {
        fld.setAccessible(true);

        Field modifiersFld = Field.class.getDeclaredField("modifiers");
        modifiersFld.setAccessible(true);
        modifiersFld.setInt(fld, fld.getModifiers() & ~Modifier.FINAL);

        fld.set(null, newVal);
    }


setFinalStatic(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.class.getDeclaredField("LOG"), new org.apache.commons.logging.Log() {

            });

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

What could be the reason for the error I am experiencing?

import requests from selenium import webdriver chrome_options = webdriver.ChromeOptions() links = {"profile.default_content_setting_values.notifications": 2} chrome_options.add_experimental_option("prefs", links) driver = webdriver.Chrome(chrome_options=c ...

"Can you provide guidance on displaying a form for a specific element based on its unique ID

I am trying to display the edit form when clicking on a specific image, but it is currently showing for all tasks. I need help in figuring out how to make it show only for one task. I attempted to use useState to change the boolean value "active" to show ...

Trouble with Vue.js: Failure to render data

Currently, I am delving into the Vue.js framework and experimenting with ways to effectively utilize this powerful JavaScript framework. Although my example is straightforward, I am facing difficulties in properly showcasing the data {} as outlined in bot ...

The timer is malfunctioning

I am new to JavaScript and looking to create a simple countdown. I came across this script: http://codepen.io/scottobrien/pen/Fvawk However, when I try to customize it with my own settings, nothing seems to happen. Thank you for any assistance! Below is ...

Issue with Java Selenium where the text entered in a textbox is not

I recently made a post seeking help with my project involving Selenium in Java for creating an account. The issue I'm facing is with using send keys, so instead, I resorted to using JavascriptExecutor. However, I'm encountering a problem where th ...

Adjusting ng-required in AngularJS for both empty values and -1

When an empty value or -1 is selected in my form, it should display an error message saying "This field is required". I have explored two possible solutions: 1. Using ng-required with regular expression. 2. Writing ctrl.$validators.required in the dir ...

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

AJAX File Upload: Sequentially Queuing Multiple Files

I am a beginner in the world of Javascript and jQuery. When I try to upload multiple files through a form, only the last file gets uploaded repeatedly. My goal is to upload each file one by one using AJAX requests asynchronously. Here's how I have ...

The background image shifts dynamically with a parallax effect as the page is scrolled

I need help solving a parallax issue that I'm currently facing. On my webpage, I have a background image positioned at the top with a parallax effect achieved through background-position: fixed. However, I now require the image to scroll along with t ...

Use JavaScript to illuminate individual words on a webpage in sequence

Is there an effective method to sequentially highlight each word on a web page? I'm thinking of breaking the words into an array and iterating through them, but I'm not sure what the best approach would be. I have experience with string replacem ...

Identify Safari browser and redirect visitors

Here is the script I am using to detect and redirect a page specifically when Safari is used: if(/safari/.test(navigator.userAgent.toLowerCase())) { window.location.href = "elsewhere.html" } Currently, it redirects in both Safari and Chrome. How can ...

The password reset feature using bcrypt is malfunctioning, as headers cannot be modified once they have been sent to the client

After developing a reset password function, the code appears as follows: router.get('/reset/:id',function(req,res,next){ User.findOne({'resetToken': req.params.id.trim()}) .exec(function(error, user){ if (error) ...

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...

Searching for an image using Xpath in Python

I am currently attempting to extract thumbnails from YouTube, with the starting point being this URL: https://www.youtube.com/results?search_query=funny The Xpath locates the image link that I need, but when I try running it through Python, I receive an ...

"Using version 4.2.6 of NodeJS, create a constructor that takes a literal object as a

Currently, I am using NodeJS v4.2.6 which unfortunately has an issue with Block-Scoped declarations not being fully supported yet. Due to certain constraints, I am restricted to this version and have resorted to including the "use strict"; line to prevent ...

Using checkboxes in an Express application

Currently, I am working on the task of parsing checkbox values into an array using express/ejs. Users are required to fill out a form and select checkboxes as shown below: Answer: Checkbox: The goal is to create two arrays from the input data: answer = ...

Implement a feature in JSP that allows users to dynamically add or remove fields before submitting the data to the database

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http- ...

Tips for integrating Tornado authentication with AngularJS

I have been experimenting with the authentication system outlined in the tornado documentation, and I am encountering a Cross-Origin Request issue when trying to integrate it with AngularJS. Is there a way to successfully combine Tornado's authentica ...

Uncover the hidden href link that has been obscured using the code javascript:void(0)

Currently, I am in the process of developing a straightforward PHP script to extract the actual link from a website that conceals the real link/key using the javascript:void(0) approach. Upon inspecting the source code, I noticed that the href link is empt ...

Javascript - Issue with Ajax causing additional commas in JSON responses

I'm attempting to send a request to a RESTful server using the HTTP module in Node.js. Due to the large response size (64 chunks, approximately 100kb), the HTTP module combines the chunks into a single string response like this: res.setEncoding(& ...