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();
    JavaScriptError.addExtension(ffProfile);
    final WebDriver driver = new FirefoxDriver(ffProfile);

    driver.get("http://somesite");

    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.chrome.ChromeDriver;
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;
    @BeforeMethod
    public void setUp() {
        System.setProperty("webdriver.chrome.driver", "{path to your chromedriver.exe}");        
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        LoggingPreferences loggingprefs = new LoggingPreferences();
        loggingprefs.enable(LogType.BROWSER, Level.ALL);
        capabilities.setCapability(CapabilityType.LOGGING_PREFS, loggingprefs);
        driver = new ChromeDriver(capabilities);
    }

    @AfterMethod
    public void tearDown() {
        driver.quit();
    }
    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());
        }
    }
    @Test
    public void testMethod() {
        driver.get("http://yourwebsite.com");
        ExtractJSLogs();
    }
}

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.

22 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
    Zahra

    Reply
    • 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.

      Reply
  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?
    Thx

    Reply
    • 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.

      Reply
      • sherin on

        Hi Ankit,
        The third approach was really good.so 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?

        Reply
      • sherin on

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

        Reply
  3. Sandeep on

    Hi AMIT RAWAT,

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

    Thank You
    Sandeep

    Reply
    • 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.

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

        hi

        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.

        Reply
  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.

    Regards,
    Sai.

    Reply
  5. Amit Rawat on

    This is how you handle the js alert.

    driver.switchTo().alert().accept();

    Reply
  6. Dharmendra on

    This is my piece of code that i am trying

    final FirefoxProfile profile = new FirefoxProfile();
    JavaScriptError.addExtension(profile);
    driver = new FirefoxDriver();

    driver.get(“my website url”);

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

    System.out.println(jsErrors);

    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.

    Reply
  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();
    JavaScriptError.addExtension(profile);
    driver = new FirefoxDriver();

    driver.get(“Application URL”);

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

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

    log.debug(jsErrors);

    Iterator itrate = jsErrors.iterator();

    while(itrate.hasNext()){

    System.out.println(itrate.next());

    }

    System.out.println(jsErrors);

    }
    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

    Reply
  8. Ujwal on

    Hi,

    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.

    Thanks,
    Ujwal

    Reply
  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 sahajamit@gmail.com

    Reply
  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…
    Anmol

    Reply
  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

    Reply
  12. 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.

    Reply
Leave a Reply

Related Posts

4 Reasons Everyone is Wrong About Blockchain: Your Guide to ... You know a technology has officially jumped the shark when iced tea companies decide they want in on the action. In case you missed that one, Long Isl...
3Pillar Recognized as a Leading Experience Designer by Forre... Fairfax-based product development company named to its second Forrester report in 2018 FAIRFAX, VA (June 18) - Today, 3Pillar Global, a global cust...
3 Cloud Optimization Projects That Will Pay for Themselves i... AWS introduced 1,430 new features and tools in 2017, including 497 in the 4th quarter alone. This means that it can be a challenge for even the mos...
The Connection Between Innovation & Story On this episode of The Innovation Engine, we'll be looking at the connection between story and innovation. Among the topics we'll cover are why story ...
Go Native (App) or Go Home, and Other Key Takeaways from App... I just returned from my first WWDC. I feel like I learned more in a week at Apple’s annual developer’s conference than I have in years of actually dev...