Check for errors on page

Let's suppose that an HTML page has several independant script tags. Let's suppose that one of them is broken. A very simple example of that would look like this:

<script>var x = 5;</script>
<script>var y = ;</script>
<script>var z = 5;</script>
<script>
    //CHECK FOR JS ERRORS HERE
</script>

Is it possible to check if there are/were any JavaScript errors on the page from the last script?

The idea behind this is to add such script at the end of each page on our development environment. That way when the QA team tests the front-end functionality and my script catches that there's a JS error on the page to alert them in a way.

Currently to achieve the same result the QA team has to test all pages with developers tool open. However most of the time they are focused on some particular functionality of the site, the developers tools is not open and some sneaky JS errors are passed by (our project has many JS scripts for external sources so such errors occur often without any changes in our code).

Upvotes: 0

Views: 462

Answers (2)

Tzach
Tzach

Reputation: 13376

There are a few options here:

  1. Add a script at the top of the page that binds to window.onerror and acts accordingly. Here is a snippet that does that.
  2. Use jshint to extract javascript from the HTML and look for syntax errors
  3. Write some unit tests

Upvotes: 3

Zach Spencer
Zach Spencer

Reputation: 1889

This is a very quick, crude, and ugly method, but it may get you started

<div id="scripts">
<script>var x = 5;</script>
<script>var y = s;</script>
<script>var z = ;</script>
</div>

<ul id="errors">

</ul>

<script>
    var sections = document.getElementById('scripts').getElementsByTagName('script');
    var errors = 0;
    for(var i = 0; i < sections.length; i++)
    {
        var section = sections[i].text
        try
        {
            eval(section);   
        }
        catch(err)
        {
            errors++;           
            var ul = document.getElementById("errors");
            var li = document.createElement("li");
            li.appendChild(document.createTextNode(err));

            var nestedUl = document.createElement("ul");
            var nestedLi = document.createElement("li");
            nestedLi.appendChild(document.createTextNode(section));
            nestedUl.appendChild(nestedLi);
            li.appendChild(nestedUl);
            ul.appendChild(li);
        }
    }
    alert(errors + " error(s)");
</script>

here is the jsfiddle http://jsfiddle.net/ws039av8/

Upvotes: 1

Related Questions