15

Is it possible to teach HTMLUnit to ignore certain javascript scripts/files on a web page? Some of them are just out of my control (like jQuery) and I can't do anything with them. Warnings are annoying, for example:

[WARN] com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument:
getElementById(script1299254732492) did a getElementByName for Internet Explorer

Actually I'm using JSFUnit and HTMLUnit works under it.

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • 1
    The HTMLUnit mailing list would be a good place to ask. The developers are on it, and they're generally very helpful. – Tom Anderson Mar 09 '11 at 00:06

5 Answers5

4

If you want to avoid exceptions because of any JavaScript errors:

 webClient.setThrowExceptionOnScriptError(false);        
John Gasper
  • 672
  • 4
  • 12
MrSmith42
  • 9,961
  • 6
  • 38
  • 49
  • 3
    Or for 2.13 and above: `webClient.getOptions().setThrowExceptionOnScriptError(false);` – Kevin Dec 16 '13 at 05:53
1

Well I am yet to find a way for that but I have found an effective workaround. Try implementing FalsifyingWebConnection. Look at the example code below.

public class PinConnectionWrapper extends FalsifyingWebConnection {

    public PinConnectionWrapper(WebClient webClient)
            throws IllegalArgumentException {
        super(webClient);
    }

    @Override
    public WebResponse getResponse(WebRequest request) throws IOException {
        WebResponse res = super.getResponse(request);
        if(res.getWebRequest().getUrl().toString().endsWith("/toolbar.js")) {
            return createWebResponse(res.getWebRequest(), "",
"application/javascript", 200, "Ok");
        }
        return res;
    }

}

In the above code whenever HtmlUnit will request for toolbar.js my code will simply return a fake empty response. You can plug-in your above wrapper class into HtmlUnit as below.

final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
new PinConnectionWrapper(webClient);
AppleGrew
  • 9,302
  • 24
  • 80
  • 124
0

If you are interested in ignoring all warning log entries you can set the log level to INFO for com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument in the log4j.properties file.

Zecas
  • 647
  • 4
  • 23
0

LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog"); java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF); java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF);

Insert this code.

Gaurab Pradhan
  • 281
  • 1
  • 5
  • 14
0

Take a look at WebClient.setScriptPreProcessor. It will give you the opportunity to modify (or in your case, stop) a given script before it is executed.

Also, if it is just the warnings getting on your nerves I would suggest changing the log level.