Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptLogging Script Errors in JavaScript

Logging Script Errors in JavaScript

In this article, we will learn to log script Errors using JavaScript. It is useful in case where scripts from any other source run/executes under the website (Ex – in an iframe) or cases where any of your viewer makes use of Browser’s Console trying to alter the script or you want to monitor your JS code for errors it may get into when put in production.

Approach: We will learn 3 methods to accomplish this task — all following the same approach but different way to implement the approach and extract the useful Information. Use whichever suits best in your case.

  1. window.addEventListener(“error”, //yourErrorLoggerFunction) — Attach an error event to the window object (DOM).
  2. document.querySelector(‘body’).onerror= //yourErrorLoggerFunction — Error Listener in the body tag -> Works both in Same Origin or Cross-Scripts of Same Origin.
  3. Create a script element and append it to the body tag of the source.

All three method can be implemented both in same source or any external source.

Note — Make sure this is the first thing to be executed by the browser (In case you are not sure it is strongly recommended to use Method 2).

Method 1: In this method, we will attach an Event Listener to our window object. Whenever any script error occurs, the attached errorLogger Function is triggered and inside the errorLoggerFunction we will extract all useful information from the event Object that our errorLogger function receives.

Javascript




window.addEventListener("error", errorLog);
 
function errorLog(event) {
 
    // Declare all variables as null
    // necessary in case of multiple
    // errors to be logged
    let msg = source = lineno = colno
                    = error = time = "";
 
    // Use prevent default in case you
    // don't want the error to be logged
    // in the console / hide the error
    event.preventDefault();
    msg = event.message;
    source = event.filename;
    lineno = event.lineno;
    colno = event.colno;
    error = event.error;
    time = event.time;
    // This time is in ms and tells us
    // time after which the error occurred
    // after the page was loaded
    // a lot other information can be
    // gathered - explore the event object
    // After extracting all the information
    // from this object now log it on your
    // server Database
}


Find the HTML Code (Method 1):

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <p style="font-size:20px;color:rgb(219, 0, 0)">
        No Errors
    </p>
 
 
 
 
 
     
    <script>
        // Make Sure addEventListener is the
        // First thing to be Executed
        window.addEventListener("error", errorLog);
 
        // String to Prepare Error Paragraph
        let errorString = "";
        const pElement = document.querySelector('p');
 
        // This console.log creates Error
        console.log(a)
 
        function errorLog(event) {
            let msg = source = lineno
                = colno = error = time = "";
            event.preventDefault();
            msg = event.message;
            source = event.filename;
            lineno = event.lineno;
            colno = event.colno;
            error = event.error;
            time = event.time;
             
            errorString = `Script Error was Found<br>
            Message-: ${msg}<br>Source Info-: ${source}
            <br>Line No-: ${lineno}<br>Column No-:
            ${colno}<br>Error Info-: ${error}<br>Time
            at which Error Occurred-: ${time}ms after
            Page Load<br><br><br><br>`;
             
            pElement.innerHTML = errorString;
        }
    </script>
</body>
 
</html>


Example -METHOD 1

Method 2: In this method, we will make use of onerror Event Handler. 

  • Step 1 — Get the body tag of that HTML Markup whichever is your case either the external HTML Markup or the Markup of the Currently loading Page.
  • Step 2 — Now when we have got the body tag in a const identifier let say const bodyTag we will add onerror Event Handler to the bodyTag.

Javascript




const bodyTag =
 
    // body tag of External HTML
    // Markup or of your page
    bodyTag.onerror = errorLogger;
 
function errorLogger(msg, url,
    lineNo, columnNo, error) {
 
    // Now process your Error
    // Information as you desire
}


Did you notice the difference in the logger function of the above two methods — Usually in case of firing of any event, the function attached to it receives an event object but in this case (method 2) we receive a pre-extracted information (For Detailed Reason Refer MDN WebDocs).

Note — Keep in mind the order of error information received in the loggerFunction- Total 5 Information — Sequence always being the same.

Find the HTML Code (Method 2):

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
 
<body onerror="errorLogger(message,
    source, lineno, colno, error)">
 
    <p style="font-size:20px;
        color:rgb(219, 0, 0)">
    </p>
 
 
 
 
 
     
    <script>
     
        // You can directly set the onerror
        // Attribute or use below 2 lines
        // Get body tag of External HTML
        // Markup or of your current page
        const bodyTag = document.querySelector('body');
        // bodyTag.onerror = errorLogger;
 
        let errorString = "";
        const pElement = document.querySelector('p');
 
        function errorLogger(msg, url,
                lineNo, colNo, error) {
                     
            // Now process your Error Information
            // as you desire
            errorString += `Script Error was Found
            <br>Message-: ${msg}<br>URL-: ${url}
            <br>Line No-: ${lineNo}<br>Column No-:
            ${colNo}<br>Error Info-: ${error}<br>
            <br><br><br>`;
             
            pElement.innerHTML += errorString;
        }
    </script>
</body>
 
</html>


 
 

Example – METHOD 2

 

Method 3: In this method, we will attach a script element to the WebPage. This method is useful in cases when we want error logger to activate at a specific time or in cases of external script execution, etc.

  • Step 1 — Get the body tag of the Markup Page you are targeting it.
  • Step 2 — Prepare a script element and append it. 

Javascript




const htmlDOM = // Get the DOM of
                //the Target Markup
 
let errScr = htmlDOM.document
        .createElement('script');
 
errScr.type = 'text/javascript';
 
errScr.innerText =
    `window.addEventListener("error",
    errorLog);function errorLog(event)
    { //process the event object}`;
 
htmlDOM.document.querySelector
        ('body').append(errScr);


Example – METHOD 3

Explanation of example — Method 3: As you can notice we have used iframe to access index.html of the same Page(Same-Origin) we planted a script in parentPage to logg errors in another WebPage.

Warning — Although you will be blocked but Beware Using these Methods in case of CROSS-SCRIPTING (CORS) (Scripts of Different Origin) without written permission from the owner of that Page.

Find the HTML Code (Method 3):

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
 
<body>
    <iframe src="index.html"
        frameborder="0">
    </iframe>
     
    <script>
        const htmlDOM = document
            .querySelector('iframe').contentDocument;
 
        let errScr = htmlDOM.createElement('script');
        errScr.type = 'text/javascript';
 
        errScr.innerText = `console.log("Script
        Loaded");window.addEventListener("error",
        errorLog);function errorLog(event){
            console.log("Error can be Processed
            Now....Use the eventObject as used
            in method-1")}`;
             
        htmlDOM.querySelector('body').append(errScr);
    </script>
</body>
 
</html>


Important Note –

  1. You can make use of both innerText and innerHTML to write the js script but we recommend using innerText as presence any HTML entity in the script would create any unwanted error.
  2. In method 3, the target and the way of getting them may differ in different cases. So the code used in the implementation of this method may differ slightly but the approach would remain same.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments