How to Capture JavaScript Errors from your Web Application

Recently, in one of my projects I was asked to come up with an automated way to capture all the JavaScript exceptions from the browser for one of our Web Applications. It is a known fact that most of the modern web applications in use today involve an extensive use of JavaScript for the client side processing which makes it all the more important to capture all JavaScript exceptions and consider each Java Script exception as a bug that needs to be fixed, irrespective of whether it is currently affecting the website functionality or the user experience.

There are many browser based tools which developers rely on to find and debug JavaScript errors like Chrome’s DevTool, Firebug , IE Developer toolbar etc. but still there exists a need of automated logging of these errors to a centralized server. To meet this requirement there are few paid solutions available today like (errorception, jslogger and muscular) which requires inserting a script tag on every web page and then it will start recording all the Java Script errors and also log them to a centralized location in real-time.

Till now we have addressed this problem from a developer’s perspective but being a tester I would also like to discuss few approaches to capture these JavaScript errors in automated tests using Selenium WebDriver. Webdriver does not support this feature and it is an issue open since 2009 and well documented on their Google group. Different people have come up with different approaches to tackle this problem and I would like to discuss each approach one by one.

Approach 1: Injecting a script on each page to catch all undetected JavaScript errors.

First we need to add a script like the following on every page


Now these errors can be extracted from your Webdriver code like this.

((JavascriptExecutor) driver).executeScript("return window.javascript_errors ");

I believe this approach is good but there are still a few drawbacks worth mentioning here. First, the JavaScript error won’t necessarily occur in the currently active window so we need to go through all the iFrames and windows to check the errors. Second problem is that it is not easy to convince your developers and management team to add this extra script in your webpages to make it testable. To overcome the second issue we can use a proxy like Browsermob or Fiddler Core to make sure our script gets injected in to the page on time to catch the onload event.

Approach 2: Using a Firefox extension to capture the errors.

You can create your own Firefox extension as Firefox allows extensions to get notified of JavaScript errors, no matter where they occur, then you can extract these errors from your Webdriver code. Marc Guillemot has created a similar extension and more details can be found on here.

Here is the simple Java example to use this extension to extract the errors.

FirefoxProfile ffProfile = new FirefoxProfile();
    final WebDriver driver = new FirefoxDriver(ffProfile);


    final List jsErrors = JavaScriptError.readErrors(driver);
    assertTrue(jsErrors.toString(), jsErrors.isEmpty());

Approach 3: Using ChromeDriver2 (WebDriver for Chrome)

In the GTAC 2013, Ken Kania from Google has explained how ChromeDriver2 is different from its previous version as it uses Chrome DevTools API and now it provides access to internals of Web App and we can do things like:

  • Query and manipulate DOM tree
  • Debug JavaScript and extracting JavaScript errors
  • Memory and Performance Profiling
  • Network Traffic Monitoring

Detailed slides of this presentation can be found here.

I would like to recommend this approach as it is very simple, robust and does not require any tweaking or workaround like the earlier approaches. Here I am posting the Java code to extract the JavaScript errors using ChromeDriver2

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class JSErrorsLogging {
private WebDriver driver;
    public void setUp() {
        System.setProperty("", "{path to your chromedriver.exe}");        
        DesiredCapabilities capabilities =;
        LoggingPreferences loggingprefs = new LoggingPreferences();
        loggingprefs.enable(LogType.BROWSER, Level.ALL);
        capabilities.setCapability(CapabilityType.LOGGING_PREFS, loggingprefs);
        driver = new ChromeDriver(capabilities);

    public void tearDown() {
    public void ExtractJSLogs() {
        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
        for (LogEntry entry : logEntries) {
            System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
    public void testMethod() {

This approach can only be used in those languages where the Logger interface has been implemented for WebDriver. We cannot use C# for this approach as according to this link, Logger interface is not yet implemented in C#.

I hope what I have shared with you through this blog will help you address the issue of how to capture JavaScript errors from your web application(s). Please do leave your comments in the box below.

Amit Rawat

Amit Rawat

Senior Quality Assurance Lead

Amit Rawat is a Senior Quality Assurance Lead at 3Pillar Global. He brings with him rich experience in automation web, desktop and mobile based applications. He has expertise on various automation tools and technologies and has been deeply involved in designing Automation solutions for Telecom, Insurance, Banking and Consumer based mobile applications. In his own words, he has “always been passionate about learning new technologies with prime area of interest in the field of Mobile automation.” Prior to joining 3Pillar Global, he has worked for various product and service based companies including Oracle, Infosys, CSC and Markit.

27 Responses to “How to Capture JavaScript Errors from your Web Application”
  1. zahra on

    Hi, I want to use approach 3.
    I have java code for testing the application with webdriver.
    I do not know where can I add your code to my code?
    How can I use it?

    Can you help me.

    Thank you so much

    • Amit Rawat on

      You can put this code in your test constructs like beforetest or beforeclass and then what ever web pages you will navigate to using the drive, it will capture all the java script errors.

  2. Yaroslav on

    Using Chromedriver2 approach is providing only 404 HTTP-request errors for me.
    Other javascript errors, like
    1)Console error
    TypeError: Cannot read property ‘split’ of undefined
    2)Uncaught TypeError: Cannot read property ‘hasClass’ of null

    are not catched.

    Any suggestion?

    • Amit Rawat on

      This approach will provide you all the errors which get listed on the java script console so as we know all the http related errors like the one which you mentioned are also listed on the browser’s javascript console.

      So here you can follow the approach to dump all these errors in a text file and later you can filter for all javascript specific errors.

      • sherin on

        Hi Ankit,
        The third approach was really if we find all links from the home page of a website and then navigate to each of them by using driver.navigate().to(“url”) inside a loop,we can find all possible errors in a website right?

      • sherin on

        What actually you meant by javascript console?-console in Eclipse?

  3. Sandeep on


    Is there any way to catch Java Script errors on Headless Browser (HTMLUnit Driver)?

    Thank You

    • Amit Rawat on

      I am not sure of it as I have never tried this. But I think approach 3 will not work in case of htmlunit driver. Approach 1 and 2 should work.

      • approach 1 will work because HTMLUnit driver is javascript based (dom) and window.javascript_errors is the jaascript function on


        Amit nice Article, i have a small doubt . if i run some script and it is failed due to pc shutdown or networkproblem or restart or some malware causes then after solving these
        Without doing anything

        how to automatically run scripts which are failed only, and how to show in the report that by the network cause the error rise or by the system shutdown the error rises or by the system virus error occured.

  4. Sai Chandra on

    Hi Amit,

    How are you?
    Is it possible to automate Java-script notifications with Web Driver and Java?
    I am working as an Intern here in Dublin, our developers told me that they were using Pnotify for Java-script notifications. Ours is a Recruitment S/W and when ever a Job is stored there is a Java-script notification that appears on the screen showing success message/error message and disappears. Can you please help in finding a solution for this problem? Thank you.


  5. Amit Rawat on

    This is how you handle the js alert.


  6. Dharmendra on

    This is my piece of code that i am trying

    final FirefoxProfile profile = new FirefoxProfile();
    driver = new FirefoxDriver();

    driver.get(“my website url”);

    final List jsErrors = JavaScriptError.readErrors(driver);
    assertTrue(jsErrors.toString(), jsErrors.isEmpty());


    In this piece of code i have tried to print the browser console errors in Selenium Webdriver console. But what i get is “[]”. Only “Square brackets” get printed in the console.

    Desired is : – I want to get the console errors either dumped in a text file or get them in email
    Or atleast get them in Webdriver Console.

    Please help with this.

    And please suggest if anything is wrong in my piece of code.

  7. Dharmendra on

    Hi Amit,

    I have tried the 2nd approach. Below is a piece of code that i have tried

    final FirefoxProfile profile = new FirefoxProfile();
    driver = new FirefoxDriver();

    driver.get(“Application URL”);

    final List jsErrors = JavaScriptError.readErrors(driver);
    assertTrue(jsErrors.toString(), jsErrors.isEmpty());

    Logger log = Logger.getLogger(“devpinoyLogger”);


    Iterator itrate = jsErrors.iterator();





    private static void assertTrue(String string, boolean empty) {
    // TODO Auto-generated method stub


    Please suggest me, where i can see the the captured errors ?

    Because whenever i run this code in the Selenium Webdriver i get [] printed in the console.

    I have tried to Log errors for this by Log4J. But i can’t see it there too.

    It will be a great help if you could share the code through which we can trace the captured errors.

    Thanks for your insightful blog

  8. Ujwal on


    I tried to incorporate approach 3.
    Here , only part of the chrome console logs are getting printed when tried the following:

    List entries = driver.manage().logs().get(LogType.BROWSER).getAll();

    I also tried to copy the logs to a file but still its evident that only part of the console logs getting copied.

    Also, the logs I see here are not exactly the same logs I see in browser’s console(F12).
    My requirement is to get the entire console logs copied to a file.

    Please help me. Thanks in advance.


  9. Amit Rawat on

    Hi All,

    I will not be available on my official email id from next week. So for all your queries you can reach me at

  10. Anmol on

    Can some one reply for how to handle JS warnings with selenium? JS error i am able to track.
    Thanks in Advance…

  11. Prasad Magre on

    Hi Amit,

    Thanks for brilliant idea, but by using the approach 3, i am able to get the error message but i am not able to get source name(js name )
    Can you please help me on this to get the JS name also, i tried all the method but no luck 🙁

    Thanks in Advance

  12. surya on

    Can Anymore help to handle toast message in selenium using java issue

  13. Shishir Kanthi on

    You could as well use simple WebDriver provided driver.Manage().Logs.GetLog(“browser”);
    This will return list of all warnings and errors which are browser logs (basically whatever you see on developer tool console) and iterate through to see if there is error you are looking for.

  14. Noman Masood on


    I tried same solution to get the IE browser logs(which are seeing in console tab e.g info messages, debug, warnings,errors etc) using selenium but not succeeded. Is there any other way to get IE browsers console logs? Your swift response will be highly appreciateable.Thanks in advance.

  15. Nayonika on

    Hi Amit,

    I tried 3rd approch using chrome Driver but i’m getting below error:

    org.openqa.selenium.remote.DesiredCapabilities chrome
    INFO: Using `new ChromeOptions()` is preferred to ``

    java.lang.NoClassDefFoundError: okhttp3/ConnectionPool

    at org.openqa.selenium.remote.internal.OkHttpClient$Factory.(
    at org.openqa.selenium.remote.internal.OkHttpClient$Factory.(
    at org.openqa.selenium.remote.http.HttpClient$Factory.createDefault(
    at org.openqa.selenium.remote.HttpCommandExecutor.(
    at JSTest.setUp(
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at org.testng.internal.MethodInvocationHelper.invokeMethod(
    at org.testng.internal.Invoker.invokeConfigurationMethod(
    at org.testng.internal.Invoker.invokeConfigurations(
    at org.testng.internal.Invoker.invokeMethod(
    at org.testng.internal.Invoker.invokeTestMethod(
    at org.testng.internal.Invoker.invokeTestMethods(
    at org.testng.internal.TestMethodWorker.invokeTestMethods(
    at org.testng.TestRunner.privateRun(
    at org.testng.SuiteRunner.runTest(
    at org.testng.SuiteRunner.runSequentially(
    at org.testng.SuiteRunner.privateRun(
    at org.testng.SuiteRunnerWorker.runSuite(
    at org.testng.TestNG.runSuitesSequentially(
    at org.testng.TestNG.runSuitesLocally(
    at org.testng.RemoteTestNGStarter.main(
    Caused by: java.lang.ClassNotFoundException: okhttp3.ConnectionPool
    at java.lang.ClassLoader.loadClass(
    at sun.misc.Launcher$AppClassLoader.loadClass(
    at java.lang.ClassLoader.loadClass(
    … 32 more

    error on line : driver = new ChromeDriver(capabilities);

  16. Steve William on

    If you read the post then you will surely get to know about the process to capture javascript error form web applications and check to know more about the errors.

  17. rober martin on

    Hey, I read the blog information and that was really good for know about JAVA and I hope from there we all get more important information by which we all will be very helpful.

Leave a Reply