'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).
Solution 1:[1]
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/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zach Spencer |
